Leetcode144

144. 二叉树的前序遍历

总体思路递归,easy等级

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var preorderTraversal = function (root) {
const ans = [];
recursion(root, ans);
return ans
};
function recursion(root, ans) {
if (root === null) return;
ans.push(root.val);
recursion(root.left, ans)
recursion(root.right, ans)
}