144.二叉树的前序遍历
题目链接:https://leetcode.cn/problems/binary-tree-preorder-traversal/
1.递归方法
前提说明根节点为val、左节点为left、右节点为right 链式存储
var preorderTraversal = function(root) {
// 用来存放前序遍历的元素
let res=[]
const headSearch=function(root){
if(root===null) return ;
res.push(root.val)
// 递归左子树
headSearch(root.left)
// 递归右子树
headSearch(root.right)
}
headSearch(root)
return res
};
2.迭代方法(使用栈实现)
var preorderTraversal=function(root,res=[]){
if(!root) return res
const stack=[root]
let cur=null
while(stack.length){
cur=stack.pop()
res.push(cur.val)
cur.right&&stack.push(cur.right)
cur.left&&stack.push(cur.left)
}
return res
}
看视频所学:
1.首先要清楚递归的底层实现原理: 函数自己调用自己|分解后的子问题求解方式一样,不同的是数据规模变小|存在递归终止条件
2.非递归的方法需要借助栈来实现。前序遍历本来是中左右,但是栈出栈方式是先进后出,所以先将右边的加入站栈,再把左边的放进栈,然后将有左右孩子的弹出,以此循坏。
145.二叉树的后序遍历
题目链接:https://leetcode.cn/problems/binary-tree-postorder-traversal/
1.递归方法
后序:左右中
var postorderTraversal = function(root) {
const res=[]
let backSearch=function(root){
if(root===null) return ;
backSearch(root.left)
backSearch(root.right)
res.push(root.val)
}
backSearch(root)
return res
};
2.迭代方法
var postorderTraversal = function(root,res=[]){
if(!root) return res
const stack=[root]
while(stack.length){
let cur=null
cur=stack.pop()
res.push(cur.val)
cur.left&&stack.push(cur.left)
cur.right&&stack.push(cur.right)}
return res.reverse()
}
看视频所学:
1.迭代方法中后序遍历,只需将前序中的遍历变为中右左,然后再翻转即可
94.二叉树的中序遍历
题目链接:https://leetcode.cn/problems/binary-tree-inorder-traversal/
1.递归方法
中序:左中右
var inorderTraversal = function(root) {
const res=[]
let midSearch=function(root){
if(root===null) return ;
midSearch(root.left)
res.push(root.val)
midSearch(root.right)
}
midSearch(root)
return res
};
2.迭代方法
var inorderTraversal = function(root,res=[]) {
const stack=[]
// 从当前根元素开始遍历
let cur=root
while(stack.length||cur){
if(cur){
stack.push(cur)
cur=cur.left
}else{
cur=stack.pop()
res.push(cur.val)
cur=cur.right
}
}
return res
}
视频所学:
1.用栈来记录我们遍历过的顺序,用指针遍历节点,孩子为空则弹出,不为空则入栈。