回忆一下递归实现
/**
/*** 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) {var retArr = []if (!root) return retArrvar hlpFunc = (r) => {if(!r) return if (r.left) { helpFunc(r.left) }retArr.push(r.val)if (r.right) { hlepFunc(r.right) }}helpFunc(root)return retArr
}
用模拟栈来实现(方法一)( 一二写法不一样,但是本质是一致)
var inorderTraversal = function(root) {var retArr = []if (!root) return retArrlet cur = rootlet stack = []while(stack.length !==0 || cur) {if (cur) {stack.push(cur)cur = cur.left} else {var tmp = stack.pop()retArr.push(temp.val)cur = temp.right}}return retArr}
用模拟栈来实现(方法二)( 一二写法不一样,但是本质是一致)
var inorderTraversal = function(root) {var retArr = []if (!root) return retArrlet cur = rootlet stack = []while(stack.length !==0 || cur) {while(cur) {stack.push(cur)cur = cur.left}var tmp = stack.pop()retArr.push(tmp.val)cur = tmp.right}return retArr
用模拟栈来实现(方法三)( 与方法一是逆向操作)
var inorderTraversal = function(root) { var retArr = []if (!root) return retArrlet stack = []let cur =rootwhile( stack.length !== 0 || cur ) {if (cur) {stack.push(cur)cur = cur.right} else {var tmp = stack.pop()retArr.push(tmp.val)cur = tmp.left}}return retArr.reverse()
}
根左右 【前序】
左根右 【中序】
根右左 【后序–逆向】
右根右 【中序–逆向】