如何求解非递归遍历
关于二叉树的遍历,我们知道有递归来遍历它;但是,递归遍历二叉树太简单了,今天,我们来看一下如何用非递归的方法遍历二叉树;
非递归前序遍历二叉树:
思路:借助栈
1:如果是空树,返回
2:非空,将根节点入栈
3:循环一下操作。
3.1:取栈顶元素cur不删除
3.2:遍历该元素
3.3:删除栈顶元素
3.4:如果cur的右子树存在,将右子树入栈
3.5:如果cur的左子树存在,将左子树入栈
以下是代码:
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list=new ArrayList<Integer>();
if(root==null){
return list;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode node=stack.pop();
list.add(node.val);
if(node.right!=null){
stack.push(node.right);
}
if(node.left!=null){
stack.push(node.left);
}
}
return list;
}
}
非递归中序遍历二叉树
思路:1:先判断根是否存在,不存在,返回
2:若根存在,先定义一个栈,将根地址给root
3:当栈不为空或者root不为空时,若root不为空时,root入栈,接下来root移向它的左子树
4:否则,说明当前root为空,栈顶元素出栈,root移向它的右子树。
以下是代码:
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
if(root==null){
return list;
}
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();
list.add(cur.val);
cur=cur.right;
}
}
return list;
}
}
非递归后序遍历二叉树
思路:1:先判断树是否为空,为空的话返回
2:找最左侧的节点(将根节点的地址赋给cur)
3:创建一个栈,保存节点
4:到这里已经到了最左侧了,现在要出栈但不删除(目的:得到最左侧的节点top来判断它的右子树)
5:如果top的右子树为空的话,打印top值,并保存这节点,再删除
6:如果top不为空,cur=top.right
下面是代码:
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> list=new ArrayList<>();
if(root==null){
return list;
}
TreeNode cur=root;
TreeNode node1=null;
Stack<TreeNode> stack = new Stack<TreeNode>();
while(!stack.isEmpty() || cur!=null){
while(cur!=null){
stack.push(cur);
cur=cur.left;
}
TreeNode top=stack.peek();
if(top.right==null || top.right==node1){
TreeNode node=stack.pop();
node1=node;
list.add(node.val);
}
else{
cur=top.right;
}
}
return list;
}
}
好了,今天就说关于二叉树的非递归遍历就说这么多了。