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

    题目如上,二叉树由根到节点上的值可以组成一个数字,该题是要求所有由根到最终节点的所有路径上的数字进行求和。

    解题的主要思路是使用前序遍历,以前面节点的值乘以10再加上当前值的形式进行数字组合,当到达树叶结点的时候总和加上组建好的路径的值。

    代码如下:

     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     
    12     private int sum = 0;
    13 
    14     public int sumNumbers(TreeNode root) {
    15     
    16         helper(root,0);
    17         
    18         return sum;
    19     }
    20     
    21     private void helper(TreeNode root, int num){
    22         if(root == null){
    23             return;
    24         }
    25         
    26         num = num*10 + root.val;
    27         if(root.left != null ){
    28             helper(root.left, num);
    29         }
    30         
    31         if(root.right != null ){
    32             helper(root.right, num);
    33         }
    34         
    35         if(root.right == null && root.left == null){
    36             sum += num;
    37         }
    38     }
    39 }

    END

  • 相关阅读:
    二叉树后序遍历
    二叉树中序遍历
    二叉树的前序遍历
    字符串转整数
    DVWA靶场——File Inclusion(文件包含)
    DVWA-CSRF
    DVWA--COMMAND INJECTION
    DVWA练习一 暴力破解
    pikachu--SSRF
    pikachu---XXE
  • 原文地址:https://www.cnblogs.com/sssysukww/p/8793958.html
Copyright © 2011-2022 走看看