【LeetCode】Binary Tree Postorder Traversal 二叉树后序遍历递归以及非递归算法

Binary Tree Postorder Traversal 
Total Accepted: 15614 Total Submissions: 50928 My Submissions
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3} ,
   1
    \
     2
    /
   3
return [3,2,1] .
Note: Recursive solution is trivial, could you do it iteratively?
【解题思路】
1、递归 左右中

Java AC

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    private ArrayList<Integer> list;
    public ArrayList<Integer> postorderTraversal(TreeNode root) {
        list = new ArrayList<Integer>();
        postOrder(root);
        return list;
    }
    private void postOrder(TreeNode root){
        if(root == null){
            return;
        }
        postOrder(root.left);
        postOrder(root.right);
        list.add(root.val);
    }
}

2、非递归
1)、需要先查找到当前节点的最左孩子,也就是一直入栈。
2)、假设到node时,左孩子为空了,这个时候出栈,栈顶元素就是当前节点node。
3)、判断栈顶元素是否为空,如果为空,说明可以直接访问根节点了,直接加入list中。
4)、如果不为空,说明需要访问右孩子,这个时候,注意将当前节点元素new一个出来,同时入栈,这一步其实是保存根节点值的。再回到1)重复处理,直到栈为空。

Java AC

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    private ArrayList<Integer> list;
    public ArrayList<Integer> postorderTraversal(TreeNode root) {
        list = new ArrayList<Integer>();
        postOrder(root);
        return list;
    }
    private void postOrder(TreeNode root){
        Stack<TreeNode> stack = new Stack<TreeNode>();
        while(root != null || !stack.isEmpty()){
            while(root != null){
                stack.push(root);
                root = root.left;
            }
            while(!stack.isEmpty()){
                root = stack.pop();
                if(root.right != null){
                	stack.push(new TreeNode(root.val));
                    root = root.right;
                    break;
                }
                list.add(root.val);
                if (stack.isEmpty()) {
					return;
				}
            }
        }
    }
}

你可能感兴趣的:(【LeetCode】Binary Tree Postorder Traversal 二叉树后序遍历递归以及非递归算法)