Given a binary tree, return the preorder traversal
of its nodes' values.
Example:
Input: [1,null,2,3]1/ \null 2/ \3 nullOutput: [1,2,3]
Follow up: Recursive solution is trivial, could you do it iteratively
?
构建 tree
var tree1 = new TreeNode(1)var tree2 = new TreeNode(2)var tree3 = new TreeNode(3)tree2.left = tree3tree1.left = nulltree1.right = tree2
首先给出递归解法, 代码很简洁。
/*** Definition for a binary tree node.* function TreeNode(val) {* this.val = val;* this.left = this.right = null;* }*//*** @param {TreeNode} root* @return {number[]}*/var preorderTraversal = function(root) {if (root) {return [root.val, ...preorderTraversal(root.left), ...preorderTraversal(root.right)]} else {return []}}
1/ \2 5/ \3 4
针对如图剖析树在先序遍历下的递归操作, 其执行过程如下:
模拟系统栈实现图解:
步骤一:1步骤二: 取出 1 并打印;25步骤三: 取出 2 并打印;345步骤四: 取出 3 并打印;步骤四: 取出 4 并打印;步骤四: 取出 5 并打印;
代码实现:
/*** Definition for a binary tree node.* function TreeNode(val) {* this.val = val;* this.left = this.right = null;* }*//*** @param {TreeNode} root* @return {number[]}*/var preorderTraversal = function(root) {const printArr = []const stack = []if (!root) return []stack.push(root)while (stack.length > 0) {const popValue = stack.pop()printArr.push(popValue.val)popValue.right && stack.push(popValue.right)popValue.left && stack.push(popValue.left)}return printArr}
使用颜色标记法
剖析树在中序遍历下的递归操作, 思路如下:
右 -> 左 -> 中
的顺序推入栈, 同时将白色元素标记为灰色元素;推荐使用颜色标记法, 它的解题思路适用于解前序、中序、后序遍历。
1/ \2 5/ \3 4
在如上所示树中, 模拟系统栈图解其执行过程如下:
gray 1white 2white 5white 2white 5gray 2white 3white 4white 5
/*** Definition for a binary tree node.* function TreeNode(val) {* this.val = val;* this.left = this.right = null;* }*//*** @param {TreeNode} root* @return {number[]}*/var preorderTraversal = function(root) {const printArr = []if (!root) return printArrconst stack = []stack.push({color: 'white',node: root})while (stack.length > 0) {const pickValue = stack.pop()const { color, node } = pickValueif (color === 'gray') {printArr.push(node.val)} else {node.right && stack.push({ color: 'white', node: node.right })node.left && stack.push({ color: 'white', node: node.left })stack.push({ color: 'gray', node })}}return printArr}
94、145