回忆一下递归实现
javascript
/**
/**
* 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 retArr
var 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
}
用模拟栈来实现(方法一)( 一二写法不一样,但是本质是一致)
javascript
var inorderTraversal = function(root) {
var retArr = []
if (!root) return retArr
let cur = root
let 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
}
用模拟栈来实现(方法二)( 一二写法不一样,但是本质是一致)
javascript
var inorderTraversal = function(root) {
var retArr = []
if (!root) return retArr
let cur = root
let 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
用模拟栈来实现(方法三)( 与方法一是逆向操作)
javascript
var inorderTraversal = function(root) {
var retArr = []
if (!root) return retArr
let stack = []
let cur =root
while( 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()
}
根左右 【前序】
左根右 【中序】
根右左 【后序--逆向】
右根右 【中序--逆向】