二叉树的迭代遍历
前序
使用栈数据结构存储节点,先遍历当前节点,然后push右节点,再push左节点(保证弹出顺序是先左后右)
js
/**
* 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) {
let result = []
if (root === null) {
return result
}
let stack = []
stack.push(root)
while (stack.length) {
const curNode = stack.pop()
result.push(curNode.val)
if (curNode.right) stack.push(curNode.right)
if (curNode.left) stack.push(curNode.left)
}
return result
};后序
使用栈数据结构存储节点,先遍历当前节点,然后push左节点,再push右节点(保证弹出顺序是先右后左),此时遍历顺序是中右左,然后反转数组,得到左右中的遍历顺序,即后序遍历
js
/**
* 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 postorderTraversal = function (root) {
let result = []
if (root == null) {
return result
}
let stack = [root]
while (stack.length) {
const top = stack.pop()
result.push(top.val)
if (top.left) stack.push(top.left)
if (top.right) stack.push(top.right)
}
result.reverse()
return result
};中序
因为要访问的元素和要处理的元素顺序是不一致的,在使用迭代法写中序遍历,就需要借用指针的遍历来帮助访问节点,栈则用来处理节点上的元素。
js
/**
* 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 inorderTraversal = function (root) {
let result = []
if (root === null) return result
let stack = []
let cur = root
while (cur !== null || stack.length) {
if (cur !== null) {
stack.push(cur)
cur = cur.left
} else {
cur = stack.pop()
result.push(cur.val)
cur = cur.right
}
}
return result
};