Sunday, November 1, 2015

[leetcode] Binary Tree Postorder Traversal

Iterative way.. 想了一会都没想出来... 网上搜到的都是很复杂的东西..
其实可以通过 root->right->left的traversal 来做...最后把结果倒转一下就好了
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        ArrayList<Integer> result = new ArrayList<Integer>();
        if (root == null){
            return result;
        }
        Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.push(root);
        while (!stack.isEmpty()){
            TreeNode temp = stack.pop();
            result.add(temp.val);
            if (temp.left != null){
                stack.push(temp.left);
            }
            if (temp.right != null){
                stack.push(temp.right);
            }
        }
        Collections.reverse(result);
        return result;
    }
}

No comments:

Post a Comment