• Sum Root to Leaf Numbers


    题目:

    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.

    这个题目简单,一次过。DFS就行,我用了个前序遍历,代码:

     1     int sumNumbers(TreeNode *root) {
     2         if(!root) return 0;
     3         int result=0,t=0;
     4         preOrder(root,&result,&t);
     5         return result;
     6     }
     7     void preOrder(TreeNode* root,int* sum,int* curSum){
     8         *curSum=*curSum*10+root->val;
     9         if(!root->left&&!root->right){//leaf node
    10             *sum+=*curSum;
    11             return;
    12         }
    13         if(root->left){
    14             preOrder(root->left,sum,curSum);
    15             *curSum/=10;
    16         }
    17         if(root->right){
    18             preOrder(root->right,sum,curSum);
    19             *curSum/=10;
    20         }
    21     }
  • 相关阅读:
    day 80 视图家族
    day 79 drf 多表关联操作
    day 78 drf 序列化
    day 77 drf中请求、渲染、解析、异常、响应模块的二次封装
    day 76 drf
    python小知识
    请求 渲染 解析 异常 响应模块
    子组件
    vue基础(2)
    vue基础
  • 原文地址:https://www.cnblogs.com/mike442144/p/3480391.html
Copyright © 2020-2023  润新知