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

    原题链接在这里:https://leetcode.com/problems/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.

    题解:

    Top-down dfs到了叶子节点加值.

    Time Complexity: O(n).

    Space: O(h), h是树的高度.

    AC Java:

     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 class Solution {
    11     public int sumNumbers(TreeNode root) {
    12         if(root == null){
    13             return 0;
    14         }
    15         
    16         int [] res = {0};
    17         dfs(root, 0, res);
    18         return res[0];
    19     }
    20     
    21     private void dfs(TreeNode root, int cur, int [] res){
    22         if(root == null){
    23             return;
    24         }
    25         
    26         cur = cur*10+root.val;
    27         
    28         if(root.left == null && root.right == null){
    29             res[0] += cur;
    30             return;
    31         }
    32 
    33         dfs(root.left, cur, res);
    34         dfs(root.right, cur, res);
    35 
    36     }
    37 }

    类似Path Sum II.

  • 相关阅读:
    [AGC020E] Encoding Subsets
    [Topcoder16346]TwoPerLine
    CF913E Logical Expression
    英语面试
    CRM
    WEB使用第三方支付服务大致流程
    OO语言 prototype 初级用法
    flash设置字体
    air 提示问题
    c#里的BYTE
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4824981.html
Copyright © 2011-2022 走看看