Friday, January 24, 2014

Sum Root to Leaf Number LeetCode

这个题是DFS。 需要注意的是,碰到根节点的时候需要判断处理一下。

public int sumNumbers(TreeNode root) {
        return helper(root, 0);
    }
    public int helper(TreeNode root, int current){
        if (root == null) return 0;
     
        current = current * 10 + root.val;
     
        int sum = 0;
        sum += helper(root.left, current);
        sum += helper(root.right, current);
     
       //千万别忘记
        if (sum == 0){
            sum = current;
        }
        return sum;
    }

Find a cleaner solution:
public int sumNumbers(TreeNode root) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        return helper(root, 0);
    }
   
    public int helper(TreeNode root, int current){
        if(root == null) return 0;
       
        if (root.left == null && root.right == null) {
            return current*10+root.val;
        }
        return helper(root.left, current*10+root.val) + helper(root.right, current*10+root.val);
    }

No comments:

Post a Comment