二叉树的定义
代码:
public class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode(){};
TreeNode(int val){this.val = val;}
TreeNode(int val,TreeNode left,TreeNode right){
this.val = val;
this.left = left;
this.right = right;
}
}
Leetcode 144. 二叉树的前序遍历
题目链接: 二叉树的前序遍历
递归遍历:主要是搞懂递归三部曲,不要太过于在意递归里面的逻辑!!!!
代码:
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
recur(root,res);
return res;
}
public void recur(TreeNode cur,List<Integer> res){
//递归终止条件
if (cur==null) return;
//执行单层递归逻辑
res.add(cur.val);
recur(cur.left,res);
recur(cur.right,res);
}
}
非递归遍历(栈):
代码:
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
Stack<TreeNode> st = new Stack<>();
if (root!=null) st.add(root);
while(!st.isEmpty()){
//栈顶树节点
TreeNode node = st.peek();
//弹出栈顶树节点
st.pop();
//如果栈顶树节点不为空,则将节点值添加到res
if (node!=null) res.add(node.val);
else continue;
//先右后左,因为栈是先入后出的
if (node.right!=null) st.add(node.right);
if (node.left!=null) st.add(node.left);
}
return res;
}
}
复杂度分析:
时间复杂度:
O
(
n
)
\mathcal{O}(n)
O(n)
空间复杂度:
O
(
n
)
\mathcal{O}(n)
O(n)
Leetcode 145. 二叉树的后序遍历
题目链接: 二叉树的后序遍历
递归遍历:
代码:
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
recur(root,res);
return res;
}
public void recur(TreeNode cur,List<Integer> res){
//递归终止条件
if (cur==null) return;
//执行单层递归逻辑
recur(cur.left,res);
recur(cur.right,res);
res.add(cur.val);
}
}
非递归遍历(栈):这里和前序遍历类似,但是要先加入左节点,再加入右节点,这样的话遍历出来的顺序为中右左,又因为后序遍历应该为左右中,所以最后反转集合就可以。
代码:
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
Stack<TreeNode> st = new Stack<>();
if (root!=null) st.add(root);
while(!st.isEmpty()){
TreeNode node = st.peek();
st.pop();
if (node!=null) res.add(node.val);
else continue;
//注意顺序
if (node.left!=null) st.add(node.left);
if (node.right!=null) st.add(node.right);
}
//反转集合中的元素
Collections.reverse(res);
return res;
}
}
复杂度分析:
时间复杂度:
O
(
n
)
\mathcal{O}(n)
O(n)
空间复杂度:
O
(
n
)
\mathcal{O}(n)
O(n)
Leetcode 94. 二叉树的中序遍历
题目链接: 二叉树的中序遍历
递归遍历:
代码:
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
recur(root,res);
return res;
}
public void recur(TreeNode cur,List<Integer> res){
//递归终止条件
if (cur==null) return;
//执行单层递归逻辑
recur(cur.left,res);
res.add(cur.val);
recur(cur.right,res);
}
}
非递归遍历:使用一个指针来遍历二叉树
代码:
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
Stack<TreeNode> st = new Stack<>();
TreeNode cur = root;
while(cur!=null||!st.isEmpty()){
if (cur!=null){
st.push(cur);
cur = cur.left;
}else{
cur = st.peek();
st.pop();
res.add(cur.val);
cur = cur.right;
}
}
return res;
}
}
复杂度分析:
时间复杂度:
O
(
n
)
\mathcal{O}(n)
O(n)
空间复杂度:
O
(
n
)
\mathcal{O}(n)
O(n)