二叉树之遍历方式

一.递归进行遍历

 //前序遍历
    public void preOrder(TreeNode root,List<Integer> list){
        if(root==null){
            return ;
        }
        list.add(root.val);
       preOrder(root.left,list);
        preOrder(root.right,list);
    }
    //中序遍历
     public void inOrder(TreeNode root,List<Integer> list){
         if(root==null){
             return;
         }
         inOrder(root.left,list);
         list.add(root.val);
         inOrder(root.right,list);
        
    }
    //后序遍历
     public void posOrder(TreeNode root,List<Integer> list){
         if(root==null)
             return;
         posOrder(root.left,list);
         posOrder(root.right,list);
         list.add(root.val);
        
    }

二.非递归进行遍历

 //前序遍历
    public void preOrder(TreeNode root,List<Integer> list){
       Stack<TreeNode> stack= new Stack<>();
        stack.add(root);
        while(!stack.isEmpty()){
            TreeNode head=stack.pop();
            list.add(head.val);
           if(head.right!=null){
               stack.push(head.right);
           }
         if(head.left!=null){
             stack.push(head.left);
         }
        }
        
    }
    //中序遍历
    public void inOrder(TreeNode root,List<Integer> list){
        Stack<TreeNode> stack=new Stack<>();
        while(!stack.isEmpty()||root!=null){
            if(root!=null){
                stack.push(root);
                root=root.left;
            }else{
                root=stack.pop();
                list.add(root.val);
                root=root.right;
            }
        }
        
    }
    //后序遍历
    public void posOrder(TreeNode root,List<Integer> list){
        Stack<TreeNode> s1=new Stack<>();
        Stack<TreeNode> s2=new Stack<>();
        s1.add(root);
        while(!s1.isEmpty()){
            root=s1.pop();
            s2.push(root);
            if(root.left!=null)
                s1.push(root.left);
            if(root.right!=null)
                s1.push(root.right);
            
        }
        while(!s2.isEmpty()){
            list.add(s2.pop().val);
        }     
    }

猜你喜欢

转载自blog.csdn.net/qq_34015596/article/details/85015456