美文网首页
P25-二叉树遍历-后序-递归

P25-二叉树遍历-后序-递归

作者: YonchanLew | 来源:发表于2021-05-20 20:45 被阅读0次
    //二叉树遍历
    /*
     * 前序遍历:根左右
     * 中序遍历:左根右
     * 后序遍历:左右根
     * 层序遍历:从上往下、从左往右
     *
     * 递归遍历:使用递归方法遍历
     * 迭代遍历:使用迭代方法实现递归函数,与递归等价
     * morris遍历
     * */
    public class P25 {
    
        /*
        *           1
        *         /   \
        *       2       3
        *     /   \
        *   4       5
        *         /   \
        *       6       7
        * */
        public static void main(String[] args) {
            TreeNode node7 = new TreeNode(7, null, null);
            TreeNode node6 = new TreeNode(6, null, null);
            TreeNode node5 = new TreeNode(5, node6, node7);
            TreeNode node4 = new TreeNode(4, null, null);
            TreeNode node3 = new TreeNode(3, null, null);
            TreeNode node2 = new TreeNode(2, node4, node5);
            TreeNode node1 = new TreeNode(1, node2, node3);
            order(node1);
        }
    
        //后序-递归
        //4-6-7-5-2-3-1
        public static void order(TreeNode root){
    
            if(root == null){
                return;
            }
    
            order(root.left);                //左
            order(root.right);               //右
            System.out.println(root.val);       //根
        }
    
        static class TreeNode{
            int val;
            TreeNode left;
            TreeNode right;
            int deep;
    
            TreeNode(){}
    
            TreeNode(int val){
                this.val = val;
            }
    
            TreeNode(int val, TreeNode left, TreeNode right){
                this.val = val;
                this.left = left;
                this.right = right;
            }
        }
    
    }
    

    相关文章

      网友评论

          本文标题:P25-二叉树遍历-后序-递归

          本文链接:https://www.haomeiwen.com/subject/fauqjltx.html