二叉树的递归遍历
前序遍历
var preorderTraversal = function(root) {
let res = []
function preorder(cur){
if(cur == null) return
res.push(cur.val)
if(cur.left) preorder(cur.left)
if(cur.right) preorder(cur.right)
}
preorder(root)
return res
};
中序遍历
var inorderTraversal = function(root) {
let res = []
function inorder(cur){
if(cur == null) return
if(cur.left) inorder(cur.left)
res.push(cur.val)
if(cur.right) inorder(cur.right)
}
inorder(root)
return res
};
后序遍历
var postorderTraversal = function(root) {
let res = []
function pestorder(cur){
if(cur == null) return
if(cur.left) pestorder(cur.left)
if(cur.right) pestorder(cur.right)
res.push(cur.val)
}
pestorder(root)
return res
};
二叉树的迭代遍历
前序遍历
var preorderTraversal = function(root) {
let stack = [root]
let res = []
if(root == null) return res
while(stack.length){
let node = stack.pop()
res.push(node.val)
if(node.right) stack.push(node.right)
if(node.left) stack.push(node.left)
}
return res
};
中序遍历
中序遍历和前后序遍历是不同的,前序遍历要访问的元素和要处理的元素顺序是一致的,都是中间节点,但是中序遍历是左中右,先访问的是二叉树顶部的节点,然后一层一层向下访问,直到到达树的最底部,再开始处理节点,这意味着 要访问的元素和要处理的元素顺序是不一致的,所以使用迭代法写中序遍历,需要借助指针的遍历来帮助访问节点,栈则用于处理节点上的元素。
var inorderTraversal = function(root) {
let stack = []
let res = []
let cur = root
while(stack.length || cur != null){
if(cur != null){
stack.push(cur)
cur = cur.left
}else {
cur = stack.pop()
res.push(cur.val)
cur = cur.right
}
}
return res
};
后序遍历
var postorderTraversal = function(root) {
let stack = []
let res = []
stack.push(root)
if(root == null) return res
while(stack.length){
let node = stack.pop()
res.push(node.val)
if(node.left) stack.push(node.left)
if(node.right) stack.push(node.right)
}
return res.reverse()
};