144. Binary Tree Preorder Traversal

问题
Given the root of a binary tree, return the preorder traversal of its nodes’ values.

先序遍历。
先将当前节点加入数组。
然后递归左子节点。
最后递归右子节点。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* Definition for a binary tree node.
* 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 {
List<Integer> ans;
public List<Integer> preorderTraversal(TreeNode root) {
ans = new ArrayList();
traversal(root);
return ans;
}

private void traversal(TreeNode root){
if (root == null){
return;
}
ans.add(root.val);
traversal(root.left);
traversal(root.right);
return;
}
}
Author

Xander

Posted on

2022-04-12

Updated on

2022-04-11

Licensed under

Comments