树的前序和后序遍历是树相关算法的基本。就不多加解释了,直接上代码。

Binary Tree Preorder Traversal

public class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> result = new LinkedList<Integer>();
        generate(result, root);
        return result;
    }

    private void generate(List<Integer> sequence, TreeNode node) {
        if (node == null)
            return;
        sequence.add(node.val);
        generate(sequence, node.left);
        generate(sequence, node.right);
    }
}

Binary Tree Postorder Traversal

public class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> result = new LinkedList<Integer>();
        generate(result, root);
        return  result;
    }

    private void generate(List<Integer> result, TreeNode node) {
        if (node == null)
            return;
        generate(result, node.left);
        generate(result, node.right);
        result.add(node.val);
    }
}

本文固定链接: http://www.js-code.com/node-js/node-js_37627.html