?LeetCode刷題實戰(zhàn)129:求根到葉子節(jié)點數(shù)字之和
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.
Note: A leaf is a node with no children.
題意
解題
class?Solution?{
????public?int?sumNumbers(TreeNode root) {
??????????if(root==null) {
????????????????return?0;
????????????}else?{
????????????????return?getNumber(root,root.val);
????????????}
????}
???public?int?getNumber(TreeNode root,int?number) {
????????if(root.left==null&&root.right==null) {
????????????return?number;
????????}
????????int?templeft=0;
????????int?tempright=0;
????????if(root.left!=null) {
????????????templeft=getNumber(root.left,root.left.val+number*10);
????????}
????????if(root.right!=null) {
????????????tempright=getNumber(root.right,root.right.val+number*10);
????????}
????????return?templeft+tempright;
????????
????}
}

