递归遍历
递归遍历的三种顺序,只需要给res.add换个位置就好
前序遍历
//前序遍历
class Solution {
public List<Integer> preorderTraversal(TreeNode root){
List<Integer> res = new ArrayList<>();
if(root == null) return res;
preorder(root,res);
return res;
}
public void preorder(TreeNode root,List res){
if(root == null) return ;
res.add(root.val);
preorder(root.left,res);
preorder(root.right,res);
}
}
中序遍历
//中序遍历
class Solution {
public List<Integer> inorderTraversal(TreeNode root){
List<Integer> res = new ArrayList<>();
if(root == null) return res;
preorder(root,res);
return res;
}
public void inorder(TreeNode root,List res){
if(root == null) return ;
preorder(root.left,res);
res.add(root.val);
preorder(root.right,res);
}
}
后序遍历
//后序遍历
class Solution {
public List<Integer> postorderTraversal(TreeNode root){
List<Integer> res = new ArrayList<>();
if(root == null) return res;
preorder(root,res);
return res;
}
public void postorder(TreeNode root,List res){
if(root == null) return ;
preorder(root.left,res);
preorder(root.right,res);
res.add(root.val);
}
}
迭代遍历
前序遍历:中左右
入栈顺序:中右左
思路:
迭代遍历模拟栈结构,首先把二叉树根节点入栈,并用while循环,把栈顶元素输出到数组,每输出一个元素,判断一次该元素下有无节点,如果有接着按右左顺序入栈
class Solution {
public List<Integer> preorderTraversal(TreeNode root){
List<Integer> res = new ArrayList<>();
if(root == null)return res;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode node = stack.pop();//将栈顶元素输出到数组中时需要弹出操作,并新建一个节点接收,在后续判断当前节点有无孩子时,也要用当前新建的节点判断,否则如果一直用root判断则会时间超出限制
res.add(node.val);
if(node.right != null) stack.push(node.right);//用node.right判断而不是root.right
if(node.left !=null) stack.push(node.left);
}
return res;
}
}
中序遍历: 左中右
遍历顺序和处理顺序不同
思路:
需要定义一个cur指针进行遍历,将cur遍历到的节点都插入到栈中,直到cur遍历到叶子节点,并且指向空,此时弹出栈顶元素(即左中右的中),并且让cur指向这个节点,将此时cur的val填入数组中,然后再将cur指向右孩子,并进行下一次判断,右孩子是否为空,若不为空则入栈,再继续遍历
class Solution{
public List<Integer> inorderTraversal(TreeNode root){
List<Integer> res = new ArrayList<>();
if(root == null) return res;
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
while(!stack.isEmpty() || cur != null){
if(cur != null) {
stack.push(cur);
cur = cur.left;
}
else{
cur = stack.pop();//需要cur指向栈顶弹出元素,否则此时cur指向空
res.add(cur.val);
cur = cur.right;/*此时指向刚栈顶弹出元素的右孩子,如果没有右孩子则继续while,进入if判断,因为没有右孩子,所以进入else继续弹出加入结果集,此时再次更新cur指向弹出的栈顶元素,即上一个元素的父节点,然后再遍历有没有右孩子,有的话入栈,然后再判断新入栈的右孩子是否是叶子节点,如果是直接入栈,重复上边操作*/
}
}
return res;
}
}
后序遍历:左右中 入栈顺序:中左右 出栈顺序:中右左
后续遍历可以通过前序遍历进行颠倒顺序得到,调转入栈顺序,然后调用reverse函数
class Solution {
public List<Integer> postorderTraversal(TreeNode root){
List<Integer> res = new ArrayList<>();
if(root == null)return res;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode node = stack.pop();//将栈顶元素输出到数组中时需要弹出操作,并新建一个节点接收,在后续判断当前节点有无孩子时,也要用当前新建的节点判断,否则如果一直用root判断则会时间超出限制
res.add(node.val);
if(node.left !=null) stack.push(node.left);
if(node.right != null) stack.push(node.right);
}
Collections.reverse(res);
return res;
}
}