zoukankan      html  css  js  c++  java
  • Given a binary tree containing digits from0-9only, each root-to-leaf path could represent a number. An example is the root-to-leaf path1->2->3which represents the number123. Find the total sum of a

     class TreeNode {
         int val;
         TreeNode left;
         TreeNode right;
         TreeNode(int x) { val = x; }
     }
    public class Solution {
        public int sumNumbers(TreeNode root) {
            if(root==null)return 0;
            return sumRoot(root,0); 
        }
    
        private int sumRoot(TreeNode root, int sum) {
            if(root==null)return 0;
            sum=sum*10+root.val;//关键
            if(root.left==null&&root.right==null)return sum;    
            return sumRoot(root.left, sum)+sumRoot(root.right, sum);//左右都要递归哦
        }
        
    }
  • 相关阅读:
    2020.7.23第十八天
    2020.7.22第十七天
    本周总结
    每日日报
    每日日报
    每日日报
    每日日报
    每日日报
    每日日报
    每日日报
  • 原文地址:https://www.cnblogs.com/softwarewebdesign/p/5508588.html
Copyright © 2011-2022 走看看