0144. Binary Tree Preorder Traversal

144. Binary Tree Preorder Traversal #

题目 #

给定二叉树的根节点 root,返回它节点值的 前序 遍历。

思路 #

代码 #

暴力解 #

public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
class Solution {
    public void traversal(TreeNode root, List<Integer> ans) {
        if (root == null) return;
        ans.add(root.val);
        traverse(root.left, ans);
        traverse(root.right, ans);
    }
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> ans = new ArrayList<>();
        traverse(root, ans);
        return ans;
    }
}