后序遍历

题目:牛客网

解题思路:

链接:https://www.nowcoder.com/questionTerminal/32af374b322342b68460e6fd2641dd1b?f=discussion
来源:牛客网

要保证根结点在左孩子和右孩子访问之后才能访问,因此对于任一结点P,先将其入栈。

如果P不存在左孩子和右孩子,则可以直接访问它;

或者P存在孩子,但是其孩子都已被访问过了,则同样可以直接访问该结点

若非上述两种情况,则将P的右孩子和左孩子依次入栈,这样就保证了

每次取栈顶元素的时候,左孩子在右孩子前面被访问,左孩子和右孩子都在根结点前面被访问。

import java.util.ArrayList;
import java.util.Stack;
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ArrayList<Integer> postorderTraversal(TreeNode root) {
        ArrayList<Integer> res = new ArrayList<Integer>();
		if(null == root){
			return res;
		}
		TreeNode pre = null;
		Stack<TreeNode> stack = new Stack<TreeNode>();
		stack.add(root);
		while(!stack.isEmpty()){
			TreeNode current = stack.peek();
			if((current.left == null && current.right == null)||(pre!=null &&(pre==current.left || pre == current.right))){
				res.add(current.val);
				stack.pop();
				pre = current;
			}
			else{
				if(current.right != null){
					stack.add(current.right);
				}
				if(current.left != null){
					stack.add(current.left);
				}
			}
		}
		return res;
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值