zoukankan      html  css  js  c++  java
  • sum-root-to-leaf-numbers——dfs

    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 all root-to-leaf numbers.

    For example,

        1
       / 
      2   3
    

    The root-to-leaf path1->2represents the number12.
    The root-to-leaf path1->3represents the number13.

    Return the sum = 12 + 13 =25.

     1 /**
     2  * Definition for binary tree
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     int sumNumbers(TreeNode *root) {
    13         if(root==NULL)
    14             return 0;
    15         res=0;
    16         dfs(root,0);
    17         return res;
    18     }
    19     void dfs(TreeNode *root,int num){
    20         if(root!=NULL){
    21             num=num*10+root->val;
    22         }
    23         if(root->left==NULL&&root->right==NULL){
    24             res+=num;
    25         }
    26         if(root->left!=NULL){
    27             dfs(root->left,num);
    28         }
    29         if(root->right!=NULL){
    30             dfs(root->right,num);
    31         }
    32     }
    33     int res;
    34 };
  • 相关阅读:
    HTML5
    9.13 开课第十天(JS脚本语音:语句:循环)
    php函数
    php基础语法
    mysql常用函数整理
    数据库经典练习题整理
    数据库练习小结
    数据库:高级查询
    CRUD操作
    SQL语句
  • 原文地址:https://www.cnblogs.com/zl1991/p/6995398.html
Copyright © 2011-2022 走看看