145. Post-order traversal recursive solution and non-recursive solution of binary tree

145. Post-order traversal recursive solution and non-recursive solution of binary tree

Given a binary tree, return its post-order traversal.

Example:

输入: [1,null,2,3]  
   1
    \
     2
    /
   3 

Output: [3,2,1]
Advanced: The recursive algorithm is very simple, can you do it through an iterative algorithm?

Solution 1: Recursion

 public List<Integer> postorderTraversal(TreeNode root) {
    
    
        List<Integer> list = new LinkedList<>();
        postorderTraversal(root,list);
        return list;
    }
    public void postorderTraversal(TreeNode root, List<Integer> list) {
    
    
           if (root==null){
    
    
               return;
           }
        postorderTraversal(root.left,list);
        postorderTraversal(root.right,list);
           list.add(root.val);
    }

Insert picture description here

Solution 2: Iteration

template

The traversal of the binary tree can be thought of based on this template. On this basis, you can always think about it carefully.

while( 栈非空 || p 非空)
{
    
    
if( p 非空)
{
    
    

}
else
{
    
    

}
}

Problem-solving ideas

1. Set node=root
2. If the node is a leaf node or the left and right nodes of the node have been visited, the element is accessed and popped,
otherwise the right and left nodes of the node are pushed into the stack in turn

public List<Integer>  postorderTraversal(TreeNode root) {
    
    
        LinkedList<Integer> list = new LinkedList<>();
        if (root==null){
    
    
            return list ;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode node=root;
        TreeNode pre=null;
        while (!stack.isEmpty()||node!=null){
    
    
             if (node!=null){
    
    
                 stack.add(node);
                 node=node.left;
             }else{
    
    
                 node = stack.peek();
                 /*如果当前节点的右节点为空获取右节点已经被访问过了*/
                 if(node.right == null || node.right == pre)
                 {
    
    
                     list.add(node.val);
                     pre = node;
                     stack.pop();
                     /*将node置为null取出下一个栈顶节点*/
                     node = null;
                 }
                 else{
    
    
                     node = node.right;
                 }

             }
             }

        return list;
    }

Insert picture description here

Guess you like

Origin blog.csdn.net/pjh88/article/details/114681307