题目
点击前往
给你二叉树的根节点 root ,返回它节点值的 前序 遍历。
示例 1:
1 2
| 输入:root = [1,null,2,3] 输出:[1,2,3]
|
示例 2:
解题思路
递归
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
var preorderTraversal = function(root) { let result = []; const dfs = function(root){ if(root == null) return; result.push(root.val); dfs(root.left); dfs(root.right); } dfs(root); return result; };
|
迭代
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
|
var preorderTraversal = function(root) { let result = []; if(!root) return result; let stack = [root]; let cur = null while(stack.length){ cur = stack.pop(); result.push(cur.val); cur.right && stack.push(cur.right); cur.left && stack.push(cur.left); } return result; };
|