[LeetCode] - Sum Root to Leaf Numbers

来源:互联网 发布:icmp是网络管理协议 编辑:程序博客网 时间:2024/05/30 23:09

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.

An example is the root-to-leaf path 1->2->3 which represents the number 123.

Find the total sum of all root-to-leaf numbers.

For example,

    1   / \  2   3

The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.

Return the sum = 12 + 13 = 25.

一般而言,binary tree的题目采用bottom-up的遍历方式时间复杂度都会小一些。但是,这个题目,我采用的是top-down的遍历方式。值得注意的是,由于题目要求找出root to leaf sum,所以要对leaf加以判断。也就是当一个node左右子树都为null的时候,这个node就为leaf。

代码如下:

/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    // top -> down    public int sumNumbersHelper(int sum, TreeNode root) {        int csum = sum*10+root.val;        if(root.left==null && root.right==null) {            return csum;        }        else {            int lsum=0, rsum=0;            if(root.left!=null) lsum+=sumNumbersHelper(csum, root.left);            if(root.right!=null) rsum+=sumNumbersHelper(csum, root.right);            return lsum+rsum;        }    }        public int sumNumbers(TreeNode root) {        if(root==null) return 0;        return sumNumbersHelper(0, root);    }}

0 0
原创粉丝点击