File tree Expand file tree Collapse file tree 2 files changed +63
-0
lines changed Expand file tree Collapse file tree 2 files changed +63
-0
lines changed Original file line number Diff line number Diff line change @@ -325,6 +325,7 @@ My accepted leetcode solutions to some of the common interview problems.
325325- [ Closest Leaf in a Binary Tree] ( problems/src/tree/ClosestLeafInABinaryTree.java ) (Medium)
326326- [ Maximum Width of Binary Tree] ( problems/src/tree/MaximumWidthOfBinaryTree.java ) (Medium)
327327- [ Recover Binary Search Tree] ( problems/src/tree/RecoverBinarySearchTree.java ) (Hard)
328+ - [ Binary Tree Postorder Traversal] ( problems/src/tree/BinaryTreePostorderTraversal.java ) (Hard)
328329
329330#### [ Two Pointers] ( problems/src/two_pointers )
330331
Original file line number Diff line number Diff line change 1+ package tree ;
2+ import java .util .*;
3+ /**
4+ * Created by gouthamvidyapradhan on 28/07/2018.
5+ * Given a binary tree, return the postorder traversal of its nodes' values.
6+
7+ Example:
8+
9+ Input: [1,null,2,3]
10+ 1
11+ \
12+ 2
13+ /
14+ 3
15+
16+ Output: [3,2,1]
17+ Follow up: Recursive solution is trivial, could you do it iteratively?
18+
19+ Solution: O(N). Maintain a stack, for every node which you pop from stack add it to result list, push left
20+ and right node to stack. Reverse the result list and return this as the answer.
21+ */
22+ public class BinaryTreePostorderTraversal {
23+ public static class TreeNode {
24+ int val ;
25+ TreeNode left ;
26+ TreeNode right ;
27+
28+ TreeNode (int x ) {
29+ val = x ;
30+ }
31+ }
32+
33+ public static void main (String [] args ) throws Exception {
34+ TreeNode root = new TreeNode (1 );
35+ root .right = new TreeNode (2 );
36+ root .right .left = new TreeNode (3 );
37+ List <Integer > result = new BinaryTreePostorderTraversal ().postorderTraversal (root );
38+ result .forEach (System .out ::println );
39+ }
40+
41+ public List <Integer > postorderTraversal (TreeNode root ) {
42+ Stack <TreeNode > stack = new Stack <>();
43+ List <Integer > result = new ArrayList <>();
44+ if (root != null ){
45+ stack .push (root );
46+ }
47+ while (!stack .isEmpty ()){
48+ TreeNode node = stack .pop ();
49+ result .add (node .val );
50+ if (node .left != null ){
51+ stack .push (node .left );
52+ } if (node .right != null ){
53+ stack .push (node .right );
54+ }
55+ }
56+ Collections .reverse (result );
57+ return result ;
58+ }
59+
60+
61+
62+ }
You can’t perform that action at this time.
0 commit comments