LeetCode Binary Tree Postorder Traversal

https://oj.leetcode.com/problems/binary-tree-postorder-traversal/

  

这个题目是用迭代的方式对树进行后根遍历,需要记录一个一个节点是否左右两个子树都已经遍历过了。


public class Solution {
	
	public List<Integer> postorderTraversal(TreeNode root) {
		class Node{
			boolean right,left;
			TreeNode treeNode;
			public Node(TreeNode node) {
				// TODO Auto-generated constructor stub
				right=false;
				left=false;
				treeNode = node;
			}
		}
		
		ArrayList<Integer>arrayList = new ArrayList<Integer>();
		Stack<Node>stack = new Stack<Node>();
		
		
		if(root==null)return arrayList;
		Node node = new Node(root);
		Node tempNodes;
		stack.push(node);
		
		while (!stack.empty()) {
			
			node = stack.peek();
			
			if(node.treeNode.left!=null&&node.left==false){
				
				node.left = true;
				TreeNode lefTreeNode = node.treeNode.left;
				while(lefTreeNode!=null){
					
					tempNodes = new Node(lefTreeNode);
					tempNodes.left = true;
					stack.push(tempNodes);
					lefTreeNode = lefTreeNode.left;
				}
			}
			else{
				if(node.treeNode.right!=null&&node.right==false){
					node.right=true;
					TreeNode rightNode = node.treeNode.right;
					tempNodes = new Node(rightNode);
					stack.push(tempNodes);
				}
				else{
					arrayList.add(node.treeNode.val);
					stack.pop();
				}
			}
		}
        return arrayList;
    }
}



你可能感兴趣的:(LeetCode Binary Tree Postorder Traversal)