遍历二叉树-非递归

这篇博客详细介绍了树的三种遍历方法:前序遍历(根-左-右),中序遍历(左-根-右)和后序遍历(左-右-根)。通过示例代码解释了如何使用栈实现这些遍历,并展示了每种遍历的逻辑流程。对于理解和实现树的遍历操作具有指导意义。
摘要由CSDN通过智能技术生成

先序遍历 ---- 根->左->右
首先我们应该创建一个Stack用来存放节点,首先我们想要打印根节点的数据,此时Stack里面的内容为空,所以我们优先将头结点加入Stack,然后打印。

之后我们应该先打印左子树,然后右子树。所以先加入Stack的就是右子树,然后左子树。
此时你能得到的流程如下:
在这里插入图片描述

public class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        if (root == null) {return res;} //特殊情况直接返回
        Stack<TreeNode> stack = new Stack<>();
        //1.先将根节点压入栈中
        stack.push(root);
        while (!stack.isEmpty()){
            //弹出栈中最上面的结点,并且将对应的结点值追加到res中
            TreeNode node = stack.pop();
            res.add(node.val);
            //把弹出的结点的左右子节点,以先右后左的形式压入栈中
            if (node.right != null){
                stack.push(node.right);
            }
            if (node.left != null){
                stack.push(node.left);
            }

        }

        return res;
    }
}

中序遍历 ---- 左->根->右

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        if (root == null) {return res;} //特殊情况直接返回

        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (!stack.isEmpty() || cur != null){
            //找到某节点的最左子结点,把寻找过程中的结点全部压入栈中
            while (cur != null){
                stack.push(cur);
                cur = cur.left;
            }//此时cur指向某节点最左子节点的空左节点  cur == null
            TreeNode node = stack.pop();
            res.add(node.val);//把该结点的值放进res集合中
            
            //判断是否最左侧这个结点是否有右子结点
            if (node.right != null){
                cur = node.right;
            }
        }
        return res;
    }
}

后序遍历 — 左->右->中
前序遍历的过程 是 中左右。
将其转化成 中右左。也就是压栈的过程中优先压入左子树,在压入右子树。
然后将这个结果返回来,就是 左右中,这里是利用栈的先进后出倒序打印。

class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        if (root == null) {return res;} //特殊情况直接返回
        //定义两个栈
		Stack<TreeNode> stack1 = new Stack<>();
		Stack<TreeNode> stack2 = new Stack<>();
		stack1.push(root);
		while (!stack1.isEmpty()) {
			TreeNode node = stack1.pop();
			stack2.push(node);
			if (node.left != null) {
				stack1.push(node.left);
			}
			if (node.right != null) {
				stack1.push(node.right);
			}
		}
		//前序遍历是中左右,改成中右左,然后压入stack2中
		// 把stack2中的元素取出来,就是左右中
		while (!stack2.isEmpty()) {
			res.add(stack2.pop().val);
		}
        }
        return res;
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值