LintCode - 二叉树的后序遍历(普通)

版权声明:本文为博主原创文章,未经博主允许不得转载。

难度:容易
要求:

给出一棵二叉树,返回其后序遍历
样例给出一棵二叉树
{1,#,2,3}

 1 
   \ 
    2 
   / 
 3

返回 [3,2,1]

思路:非递归
/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    public ArrayList postorderTraversal(TreeNode root) {
        ArrayList result = new ArrayList();
        Stack stack = new Stack();
        TreeNode prev = null; // previously traversed node
        TreeNode curr = root;
    
        if (root == null) {
            return result;
        }
    
        stack.push(root);
        while (!stack.empty()) {
            curr = stack.peek();
            if (prev == null || prev.left == curr || prev.right == curr) { // traverse down the tree
                if (curr.left != null) {
                    stack.push(curr.left);
                } else if (curr.right != null) {
                    stack.push(curr.right);
                }
            } else if (curr.left == prev) { // traverse up the tree from the left
                if (curr.right != null) {
                    stack.push(curr.right);
                }
            } else { // traverse up the tree from the right
                result.add(curr.val);
                stack.pop();
            }
            prev = curr;
        }
    
        return result;
    }
}
思路:递归
/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    public ArrayList postorderTraversal(TreeNode root) {
        ArrayList result = new ArrayList();
    
        if (root == null) {
            return result;
        }
    
        result.addAll(postorderTraversal(root.left));
        result.addAll(postorderTraversal(root.right));
        result.add(root.val);
    
        return result;   
    }
}

你可能感兴趣的:(LintCode - 二叉树的后序遍历(普通))