[ACE] PreOrder and InOrder traversal on LeetCode
Binary Tree PreOrder Traversal We have discussed tree before, but today i found a similar question on LeetCode, i’d like to analysis the question here again. The question is: 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? My Answer is as follows: Basic idea: what i do for this question is to store the tree nodes in Stack. Thus, we need to push the right child first and then left child. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public ArrayList<Integer> preorderTraversal(TreeNode root) { ArrayList<Integer> arrayList = new ArrayList<Integer>(); if(root == null){ return arrayList; } Stack<Tr...