Wednesday, January 14, 2015

Binary Tree Preorder Traversal (LeetCode Tree)

Question: 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].

Idea: Recursion

Time: O(n) Space: O(n)

Code:
 public class Solution {  
   public List<Integer> preorderTraversal(TreeNode root) {  
     List<Integer> result=new ArrayList<Integer>();  
     visit(root,result);  
     return result;  
   }  
   public void visit(TreeNode root, List<Integer> result)  
   {  
     if(root==null)  
       return;  
     result.add(root.val);  
     visit(root.left,result);  
     visit(root.right,result);  
   }  
 }  

No comments:

Post a Comment