144. Binary Tree Preorder Traversal 二叉树先序遍历

Given the root of a binary tree, return the preorder traversal of its nodes‘ values.

 

Example 1:

144. Binary Tree Preorder Traversal 二叉树先序遍历

Input: root = [1,null,2,3]
Output: [1,2,3]

Example 2:

Input: root = []
Output: []

Example 3:

Input: root = [1]
Output: [1]

Example 4:

144. Binary Tree Preorder Traversal 二叉树先序遍历

Input: root = [1,2]
Output: [1,2]

Example 5:

144. Binary Tree Preorder Traversal 二叉树先序遍历

Input: root = [1,null,2]
Output: [1,2]


我的一个认知误区:前序遍历不是左中右,而是根结点 ---> 左子树 ---> 右子树,根节点在前面。
前序的基础上,加一个list来辅助添加就行了

 

参考:https://leetcode.com/problems/binary-tree-preorder-traversal/discuss/45468/3-Different-Solutions

public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> pre = new LinkedList<Integer>();
        preHelper(root,pre);
        return pre;
    }
    public void preHelper(TreeNode root, List<Integer> pre) {
        if(root==null) return;
        pre.add(root.val);
        preHelper(root.left,pre);
        preHelper(root.right,pre);
    }

 

 
 

144. Binary Tree Preorder Traversal 二叉树先序遍历

上一篇:Codeforces Round #713 (Div. 3) F. Education 超详细思考过程


下一篇:Solution -「ABC 209F」Deforestation