zoukankan      html  css  js  c++  java
  • 129.Sum Root to Leaf Numbers

    题目链接

    题目大意:给出一个二叉树,从根节点到叶的路径上的数值组成一个int型的数值,将所有路径上的所有数值相加得到最总和。例子如下:

    法一:DFS。从根节点到叶节点,在路径上每到达一个节点,则计算出其值,然后DFS进去即可。代码如下(耗时1ms):

     1     public int sumNumbers(TreeNode root) {
     2         if(root == null) {
     3             return 0;
     4         }
     5         int res = 0;
     6         res = dfs(root, 0, res);
     7         return res;
     8     }
     9     private static int dfs(TreeNode root, int cnt, int res) {
    10         //计算最后叶节点的数值,由于前面有判断进来的节点是否为null,所以这里root一定是非空节点
    11         if(root.left == null && root.right == null) {
    12             res += cnt * 10 + root.val;
    13             return res;
    14         }
    15         //计算根节点的数值
    16         cnt = cnt * 10 + root.val;
    17         //如果有左孩子,遍历左孩子
    18         if(root.left != null) {
    19             res = dfs(root.left, cnt, res);
    20         }
    21         //如果有右孩子,遍历右孩子
    22         if(root.right != null) {
    23             res = dfs(root.right, cnt, res);
    24         }
    25         return res;
    26     }
    View Code
  • 相关阅读:
    数位DP
    组合
    卢卡斯Lucas&扩展卢卡斯
    [HNOI2014]道路堵塞
    [模板]三维凸包(无讲解)
    [CF526G]Spiders Evil Plan
    [CCPC2019 ONLINE]H Fishing Master
    [CCPC2019 ONLINE]E huntian oy
    [CF1037H]Security
    [CF1037F]Maximum Reduction
  • 原文地址:https://www.cnblogs.com/cing/p/8806375.html
Copyright © 2011-2022 走看看