Skip to main content

Posts

Showing posts from August, 2017

[LeetCode Solution 145] Binary Tree Postorder Traversal

[LeetCode Solution 145]: Binary Tree Postorder Traversal Question: 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] . Approach #1 Recursive [Accepted] Detail Explanation The first method to solve this problem is using recursive. This is the classical method and straightforward. we can define a helper function to implement recursion. The java code is as follows: Java public class Solution { public List<Integer> postorderTraversal (TreeNode root) { List<Integer> res = new ArrayList<>(); helper(root, res); return res; } public void helper (TreeNode root, List<Integer> res) { if (root != null ) { if (root.left != null ) { helper(root.left, res); } if (root.right != null ) { helper(root.right, res); } res.add(root.val); } } } Complexity Analysis Time complexity :

[LeetCode Solution 144] Binary Tree Preorder Traversal

[LeetCode 144] Given a binary tree, return the  preorder  traversal of its nodes' values. For example: Given binary tree, {1,#,2,3} 1 \ 2 / 3 return  [1,2,3] . Note:  Recursive solution is trivial, could you do it iteratively? ***************************************************************************************************************** Solution:  [My Solution on LeetCode] Approach #1 Recursive Detail Explanation The first method to solve this problem is using recursive. This is the classical method and straightforward. we can define a helper function to implement recursion. The java code is as follows: Java public List<Integer> preorderTraversal (TreeNode root) { List<Integer> res = new ArrayList<>(); helper(root, res); return res; } public void helper (TreeNode root, List<Integer> res) { if (root != null ) { res.add(root.val); if (root.left != null ) { helper(roo