前言
“这是我参与8月更文挑战的第8天,活动详情查看:8月更文挑战”
二叉树相关的问题, 因此总结下二叉树前中后遍历的实现方式
- NC45 实现二叉树先序,中序和后序遍历(中等)
二叉树的前序遍历
思路分析 : 二叉树的前序遍历顺序 是 根 左 右
准备一个 栈, 先把根节点放入栈中, 然后当栈不为空时, 从里面弹出一个节点 node,如果 node 节点的右孩子节点不为空时压入栈中, 然后判断 node 节点的左孩子节点,不为空就压入栈中。 当栈为空时 遍历结束,返回 List
List<Integer> preOrder(TreeNode root){
List<Integer> ans = new ArrayList<>();
if(root == null) return ans;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode node = stack.pop();
ans.add(node.val);
if(node.right !=null){
stack.push(node.right);
}
if(node.left !=null){
stack.push(node.left);
}
}
return ans;
}
二叉树的中序遍历
思路分析: 二叉树的中序遍历顺序 是 左 根 右
准备一个栈, 当栈非空或者 root 不为 null 时开始循环 当 root 不为 null时, 将其压入栈中, 将root 置为 root 的左子节点 循环此过程,直至root 为null
root 为 null 时, 从栈中弹出一个节点 node,添加到 ans 集合中, node 节点的右子节点不为null 时, 将root 置为 node 节点的右子节点 继续循环
AC 代码:
List<Integer> inOrder(TreeNode root){
List<Integer> ans = new ArrayList<>();
if(root == null) return ans ;
Stack<TreeNode> stack = new Stack<>();
while(!stack.isEmpty() || root != null){
while(root != null){
stack.push(root);
root = root.left;
}
TreeNode node = stack.pop();
ans.add(node.val);
if(node.right != null){
root = node.right;
}
}
return ans;
}
二叉树的后序遍历
思路分析: 二叉树的后序遍历顺序 是 左 右 根
准备一个栈 和一个 pre 变量记录上一次添加到 ans 中的节点
当栈非空或者 root 不为 null 时开始循环 当 root 不为 null时, 将其压入栈中, 将root 置为 root 的左子节点 循环此过程,直至root 为null
root 为 null 时, 从栈中弹出一个节点 node, 如果 node 没有 右子节点 或者 node 的右子节点是 pre 节点 ,那么将node 添加到 ans 中, 更新 pre 节点 否则 将 node 节点重新压回到栈中, 将root 置为 node 节点的右子节点 继续循环
AC 代码:
List<Integer> postOrder(TreeNode root){
List<Integer> ans = new ArrayList<>();
if(root == null){
return ans ;
}
Stack<TreeNode> stack = new Stack<>();
TreeNode pre = null;
while(!stack.isEmpty() || root != null){
while(root != null){
stack.push(root);
root = root.left;
}
TreeNode node = stack.pop();
if(node.right == null || node.right == pre){
ans.add(node.val);
pre = node;
}else{
stack.push(node);
root = node.right;
}
}
return ans;
}