1. 程式人生 > >5.30 Tree Traversal + Tree manipulation

5.30 Tree Traversal + Tree manipulation

二叉樹 vid RR preorder In root ati tree lis

    1. Binary Tree Preorder Traversal

題目:對一棵二叉樹進行前序遍歷,並將結果存在一個List

public class Solution {
    public ArrayList<Integer> preorderTraversal(TreeNode root) {
        ArrayList<Integer> result = new ArrayList<Integer>();
        // null or leaf
        if (root == null) {
            return result;
        }

        // Divide
        ArrayList<Integer> left = preorderTraversal(root.left);
        ArrayList<Integer> right = preorderTraversal(root.right);

        // Conquer
        result.add(root.val);
        result.addAll(left);
        result.addAll(right);
        return result;
    }
}

5.30 Tree Traversal + Tree manipulation