zoukankan      html  css  js  c++  java
  • 129. 求根到叶子节点数字之和(递归

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        int ans=0;//最后的结果
        public int sumNumbers(TreeNode root) {
            dfs(root,0);
            return ans;
        }
        public void dfs(TreeNode root,int sum)
        {
            if(root==null)return;//根节点为空,直接返回
            int sum1=sum*10+root.val;//如果根节点不为空,则当前这个路径的代表的数字是sum*10+root.val
            if(root.left==null&&root.right==null)//假如到了叶子结点,说明当前路径代表的数字已经找到了,把数字加到最后的结果集合就好
            {
                ans+=sum1;
            }
            dfs(root.left,sum1);
            dfs(root.right,sum1);
        }
    }
    

      

  • 相关阅读:
    js触摸屏案例
    Docker
    Docker 镜像加速
    Docker 命令大全
    linux gpasswd
    Docker基础教程
    PHP输出毫秒时间戳
    PHP Variable handling 函数
    Partition Array by Odd and Even
    Median
  • 原文地址:https://www.cnblogs.com/lzh1043060917/p/12893268.html
Copyright © 2011-2022 走看看