Binary Tree Postorder Traversal 두 갈래 트리 후속 스트리밍 @LeetCode

1831 단어
반복 해법은 그 면접 총결산2에 썼다
package Level3;

import java.util.ArrayList;

import Utility.TreeNode;

/**
 * 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].

Note: Recursive solution is trivial, could you do it iteratively?
 *
 */
public class S134 {

	public static void main(String[] args) {

	}
	
	public ArrayList<Integer> postorderTraversal(TreeNode root) {
		ArrayList<Integer> ret = new ArrayList<Integer>();
		
		if(root == null){
			return ret;
		}
		
		rec(root, ret);
		return ret;
    }
	
	public void rec(TreeNode root, ArrayList<Integer> ret){
		if(root == null){
			return;
		}
		rec(root.left, ret);
		rec(root.right, ret);
		ret.add(root.val);
	}

}
/**
 * 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> ret = new ArrayList<Integer>();
        if(root == null){
            return ret;
        }
        Stack<TreeNode> s1 = new Stack<TreeNode>();
        Stack<TreeNode> s2 = new Stack<TreeNode>();
        s1.push(root);
        while(!s1.isEmpty()){
            TreeNode cur = s1.pop();
            s2.push(cur);
            if(cur.left != null){
                s1.push(cur.left);
            }
            if(cur.right != null){
                s1.push(cur.right);
            }
        }
        while(!s2.isEmpty()){
            ret.add(s2.pop().val);
        }
        return ret;
    }
}

좋은 웹페이지 즐겨찾기