创建二叉树结构
function TreeNode(val) {
this.val = val;
this.left = this.right = null;
}
let root = new TreeNode(1)
let node2 = new TreeNode(2)
let node3 = new TreeNode(3)
let node4 = new TreeNode(4)
let node5 = new TreeNode(5)
let node6 = new TreeNode(6)
let node7 = new TreeNode(7)
root.left = node2
root.right = node3
node2.left = node4
node2.right = node5
node3.left = node6
node3.right = node7
// 二叉树结构:
// 1
// / \
// / \
// 2 3
// / \ / \
// 4 5 6 7
前序遍历
利用栈结构实现,左子树后入先出
var preorderTraversal = function(root) {
if(!root) {
return []
}
let result = [],
stack = [root]
while(stack.length) {
// 弹栈顺序:中->左->右
let curr = stack.pop()
result.push(curr.val)
if(curr.right) {
stack.push(curr.right)
}
if(curr.left) {
stack.push(curr.left)
}
}
return result
};
console.log(preorderTraversal(root))
// 结果: [ 1, 2, 4, 5, 3, 6, 7 ]
中序遍历
继续利用栈结构实现,先对左子树入栈直至左子树为空,然后弹出节点,开始对右子树入栈
var inorderTraversal = function(root) {
if(!root) {
return []
}
let result = [],
stack = []
while(stack.length || root) {
// 弹栈顺序:左->中->右
if(root) {
stack.push(root)
root = root.left
} else {
let curr = stack.pop()
result.push(curr.val)
root = curr.right
}
}
return result
};
console.log(inorderTraversal(root))
// 结果: [ 4, 2, 5, 1, 6, 3, 7 ]
后序遍历
利用前序遍历实现的思路,先对左子树入栈,后对右子树入栈,即以中->右->左顺序弹栈,将其遍历结果逆转即是后序遍历的结果
var postorderTraversal = function(root) {
if(!root) {
return []
}
let result = [],
stack = [root]
while(stack.length) {
// 弹栈顺序:中->右->左
// 逆转:左->右->中
let curr = stack.pop()
result.push(curr.val)
if(curr.left) {
stack.push(curr.left)
}
if(curr.right) {
stack.push(curr.right)
}
}
return result.reverse()
};
console.log(postorderTraversal(root))
// 结果: [ 4, 5, 2, 6, 7, 3, 1 ]