Given a binary tree, return the inorder traversal of its nodes' values.
Example:
Input: [1,null,2,3]1/ \null 2/3Output: [1,3,2]
Follow up: Recursive solution is trivial, could you do it iteratively?
/*** Definition for a binary tree node.* function TreeNode(val) {* this.val = val;* this.left = this.right = null;* }*//*** @param {TreeNode} root* @return {number[]}*/var inorderTraversal = function(root) {if (root) {return [...inorderTraversal(root.left), root.val, ...inorderTraversal(root.right)]} else {return []}}
使用颜色标记法
剖析树在中序遍历下的递归操作, 思路如下:
右 -> 中 -> 左
的顺序推入栈, 同时将白色元素标记为灰色元素;4/ \2 5/ \1 3
在如上所示树中, 模拟系统栈图解其执行过程如下:
white 2gray 4white 5white 1gray 2white 3gray 4white 5gray 1gray 2white 3gray 4white 5white 3gray 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 inorderTraversal = 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 })stack.push({ color: 'gray', node })node.left && stack.push({ color: 'white', node: node.left })}}return printArr}
144、94、145