본문 바로가기
알고리즘

[LeetCode] 145. Binary Tree Postorder Traversal

by irerin07 2023. 12. 6.
728x90
class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
	    LinkedList<Integer> ans = new LinkedList<>();
	    Stack<TreeNode> stack = new Stack<>();
        
	    if (root == null) { 
            return ans;
        }
        
	    stack.push(root);
        
	    while (!stack.isEmpty()) {
		    TreeNode cur = stack.pop();
		    ans.addFirst(cur.val);
            
		    if (cur.left != null) {
			    stack.push(cur.left);
		    }
            
		    if (cur.right != null) {
			    stack.push(cur.right);
		    } 
            
	    }
        
	    return ans;
    }
    
}

Postorder Traversal은

 

Left, Right, Visit 의 순서로 기억하면 된다.

728x90