LeetCode 解题报告 Binary Tree Postorder Traversal

Given a binary tree, return the postorder traversal of its nodes' values.

For example:
Given binary tree {1,#,2,3},

   1
    \
     2
    /
   3

return [3,2,1].

分析:

不用递归来求二叉树的后序遍历,那首先等想到的就是用栈来模拟。

首先从根节点开始,遍历左子树并进站。

直至左子树空,然后弹出最后一个进入栈的元素,并判断其右子树

如果右子树为空,或者访问过了,就将其加入到结果集中,

否则,现将弹出的结点再次进栈,然后指向其右结点

public List<Integer> postorderTraversal(TreeNode root) {
        Stack<TreeNode> stack = new Stack<TreeNode>();
        List<Integer> result = new LinkedList<Integer>();
        TreeNode node = root;
        do{
        	//将左子树入栈
        	while(node != null){
        		stack.push(node);
        		node = node.left;
        	}
        	TreeNode temp = null;
        	while(!stack.empty()){
        		node = stack.peek();
        		stack.pop();
        		//这个节点没有右孩子,或者被访问过了
        		if(node.right == temp){
        			result.add(node.val);
        			temp = node;	
        		}else{
        			stack.push(node);
        			node = node.right;
        			break;
        		}
        	}
        }while(!stack.isEmpty());
        return result;
    }


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值