Sunday, August 21, 2016

Leetcode 129. Sum Root to Leaf Numbers

Answer 1:
 /**  
  * Definition for a binary tree node.  
  * public class TreeNode {  
  *   public int val;  
  *   public TreeNode left;  
  *   public TreeNode right;  
  *   public TreeNode(int x) { val = x; }  
  * }  
  */  
 public class Solution {  
   public int SumNumbers(TreeNode root) {  
     if (root == null)  
     {  
       return 0;  
     }  
     List<string> list = helper(root);  
     int sum = 0;  
     foreach(string s in list)  
     {  
       sum += Int32.Parse(s);  
     }  
     return sum;  
   }  
   List<string> helper(TreeNode root)  
   {  
     List<string> list = new List<string>();  
     if (root.left == null && root.right == null)  
     {  
       list.Add("" + root.val);  
     }  
     if (root.left != null)  
     {  
       List<string> left = helper(root.left);  
       foreach (string s in left)  
       {  
         list.Add(root.val + s);  
       }  
     }  
     if (root.right != null)  
     {  
       List<string> right = helper(root.right);  
       foreach (string s in right)  
       {  
         list.Add(root.val + s);  
       }  
     }  
     return list;  
   }  
 }  
Answer 2:
 /**  
  * Definition for a binary tree node.  
  * public class TreeNode {  
  *   public int val;  
  *   public TreeNode left;  
  *   public TreeNode right;  
  *   public TreeNode(int x) { val = x; }  
  * }  
  */  
 public class Solution {  
   public int SumNumbers(TreeNode root) {  
     if (root == null)  
     {  
       return 0;  
     }  
     List<string> list = new List<string>();  
     string cur = "";  
     helper(root, cur, list);  
     int sum = 0;  
     foreach(string s in list)  
     {  
       sum += Int32.Parse(s);  
     }  
     return sum;  
   }  
   void helper(TreeNode root, string cur, List<string> list)  
   {  
     if (root.left == null && root.right == null)  
     {  
       cur += root.val;  
       list.Add(cur);  
       return;  
     }  
     if (root.left != null)  
     {  
       helper(root.left, cur + root.val, list);  
     }  
     if (root.right != null)  
     {  
       helper(root.right, cur + root.val, list);  
     }  
   }  
 }  

No comments:

Post a Comment