题目:
Given a binary tree, return the preorder traversal of its nodes' values.

For example:
Given binary tree {1,#,2,3},
1

\
 2
/

3
return [1,2,3].

解答:
这里有三种方法,三种方法是三种思考问题的思路,都掌握才好。
1.Iterative的解法:

public List<Integer> preorderTraversal(TreeNode root) {
    List<Integer> result = new ArrayList<Integer>();
    Stack<TreeNode> stack = new Stack<TreeNode>();
    if (root == null) return result;
    
    stack.push(root);
    while (!stack.isEmpty()) {
        TreeNode node = stack.pop();
        if (node.right != null) {
            stack.push(node.right);
        }
        if (node.left != null) {
            stack.push(node.left);
        }
        result.add(node.val);
    }
    return result;
}

2.Recursive的解法:

public void Traverse(TreeNode root, List<Integer> result) {
    if (root == null) return;
    
    result.add(root.val);
    Traverse(root.left, result);
    Traverse(root.right, result);
}

public List<Integer> preorderTraversal(TreeNode root) {
    List<Integer> result = new ArrayList<Integer>();
    Traverse(root, result);
    return result;
}

3.Divide & Conquer的解法

public List<Integer> preorderTraversal(TreeNode root) {
    List<Integer> result = new ArrayList<Integer>();
    if (root == null) return result;
    
    List<Integer> left = preorderTraversal(root.left);
    List<Integer> right = preorderTraversal(root.right);
    
    result.add(root.val);
    result.addAll(left);
    result.addAll(right);
    
    return result;
}

guoluona
199 声望14 粉丝