代码随想录的第十二天(二叉树)
144. 二叉树的前序遍历
递归算法
var preorderTraversal = function(root) {
var res = []
function des (root) {
if (root === null) return
res.push(root.val)
des(root.left)
des(root.right)
}
des(root)
return res
};
思路:
1、首先明白前序遍历是中左右
2、然后去存储当前的中节点,然后一直去遍历左节点,左节点全部完事儿后再去遍历所有的右节点
技巧:
1、前中后序遍历的那个方位就是root.val的位置
2、递归按照前中后序的遍历的顺序进行遍历就行
迭代遍历:
var preorderTraversal = function(root) {
const res = []
if (!root) return res
const stack = [root]
while (stack.length) {
const cur = stack.pop()
res.push(cur.val)
cur.right && stack.push(cur.right)
cur.left && stack.push(cur.left)
}
return res
};
思路:
1、就是利用栈进行遍历
2、首先先将中间节点放入栈中,然后取出来加进去数组,当加进去的这个中节点有左右子节点的时候,先将右子树的节点加入栈中(因为栈是后进先出),然后再加入左子树的节点,依次遍历
145. 二叉树的后序遍历
递归算法:
var postorderTraversal = function(root) {
const res = []
function des (root) {
if (root === null) return
des(root.left)
des(root.right)
res.push(root.val)
}
des(root)
return res
};
迭代法:
var postorderTraversal = function(root) {
const res = []
if (!root) return res
const stack = [root]
while (stack.length) {
const cur = stack.pop()
res.push(cur.val)
cur.left && stack.push(cur.left)
cur.right && stack.push(cur.right)
}
return res.reverse()
};
思路:
1、继承前序遍历,前序遍历迭代法顺序是中左右,然后先push右再push左
2、那么代码左右push顺序调整,就变成了中右左,然后再将得到的数组进行反转,就变成了左右中,即是后序遍历
94. 二叉树的中序遍历
递归算法:
var inorderTraversal = function(root) {
const res = []
function des(root) {
if (root === null) return
des(root.left)
res.push(root.val)
des(root.right)
}
des(root)
return res
};
迭代算法:
var inorderTraversal = function(root) {
const res = []
const stack = []
let cur = root
while (cur || stack.length) {
if (cur) {
stack.push(cur);
cur = cur.left
} else {
cur = stack.pop()
res.push(cur.val)
cur = cur.right
}
}
return res
};
思路:
1、首先将根节点推入栈中,然后如果根节点有左子节点,就一直去遍历,直到左子节点下面为空
2、弹出左子节点,推入数组,然后以这个节点为中节点,判断下面有没有右子节点,如果有就加入,没有就继续往上层走,依次往复