二叉树的前序、中序、后序遍历非递归实现

思路: 借助栈来实现

前序遍历:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
// 前序
public List<Integer> preorderTraversal(TreeNode root) {
		ArrayList<Integer> ans = new ArrayList<Integer>();
		Stack<TreeNode> s = new Stack<TreeNode>();
		while(root != null || !s.isEmpty()) {
			while(root != null) {
				ans.add(root.val);
                s.push(root);
				root = root.left;
			}
			if (!s.isEmpty()) {
				TreeNode pop = s.pop();
				root = pop.right;
			}
		}
		 return ans;
	}

中序:

 public List<Integer> inorderTraversal(TreeNode root) {
        ArrayList<Integer> ans = new ArrayList<Integer>();
        Stack<TreeNode> s = new Stack<TreeNode>();
        while (root != null || !s.isEmpty()) {
        	
        	while(root != null) {
        		s.push(root);
        		root = root.left;
        	}
        	// root == null
        	if (!s.isEmpty()) {
        		TreeNode pop = s.pop();
        		ans.add(pop.val);
        		root = pop.right;
        	}
        }
        return ans;
    }

后序遍历:

三种中最难的,要保证左孩子和右孩子都已被访问并且左孩子在右孩子前访问才能访问根结点,没法直接从左儿子跳到右儿子。

可以借鉴https://www.cnblogs.com/SHERO-Vae/p/5800363.html 的两种思路

另外,有种比较巧妙的思路,后序遍历是(“左右根")。我们反向遍历,即("根右左" ),存答案也用反向存(”左右根“),这样就和前序遍历类似了。用linkedList(当作链表用)来存遍历结果(采用头插法)。

 public List<Integer> postorderTraversal(TreeNode root) {
       LinkedList<Integer> ans = new LinkedList<Integer>();
       Stack<TreeNode> s=new Stack<TreeNode>();
       while(root != null || !s.isEmpty()){
           if(root != null){
               s.push(root);
               ans.addFirst(root.val);//头插法
               root = root.right;
           }else{
               TreeNode pop=s.pop();
               root = pop.left;
           }
       }
       return ans;
   }

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值