zoukankan      html  css  js  c++  java
  • an interseting binary tree questions

    题目:
    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 class Solution {
     2 public:
     3     int sumNumbers(TreeNode *root) {
     4         int sum = 0;
     5         if(!root) return sum;
     6         return preOrder(root,sum);
     7     }
     8     int preOrder(TreeNode *root, int sum)
     9     {
    10         if(!root) return 0;
    11          sum = sum*10 + root->val;
    12         if(root->left == NULL && root->right == NULL)
    13         {
    14             return sum;
    15         }        
    16         return preOrder(root->left,sum)+preOrder(root->right,sum);
    17     }
    18 };
  • 相关阅读:
    SPA项目开发之登录
    使用vue-cli搭建SPA项目
    ElementUI入门和NodeJS环境搭建
    struts文件上传
    Struts增删改查
    struts
    Maven
    easyui三
    EasyUi权限
    自定义MVC三
  • 原文地址:https://www.cnblogs.com/dzy521/p/9144705.html
Copyright © 2011-2022 走看看