Given the root
of a binary tree, return the preorder traversal of its nodes‘ values.
Example 1:
Input: root = [1,null,2,3]
Output: [1,2,3]
Example 2:
Input: root = []
Output: []
Example 3:
Input: root = [1]
Output: [1]
Example 4:
Input: root = [1,2]
Output: [1,2]
Example 5:
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);
}