LeetCode 144. Binary Tree Preorder Traversal

题目要求:
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].

Note: Recursive solution is trivial, could you do it iteratively?

使用recursion的方式进行处理

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List preorderTraversal(TreeNode root) {
        List list = new ArrayList<>();
        traversal(list, root);
        return list;
    }
    private void traversal(List list, TreeNode node) {
        if (node == null) {
            return;
        }
        list.add(node.val);
        traversal(list, node.left);
        traversal(list, node.right);
    }
}

你可能感兴趣的:(leetcode)