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

    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.

    题目大意:给一个二叉树,每个节点都是0-9之间的数字,从根节点到叶结点表示一个数字,求所有的这些数字的和。

    解题思路:这道题应该是考察DFS,可以直接DFS求解,或者中序遍历用queue也可以做,最近做题没什么状态,脑袋一团浆糊。

        public int sumNumbers(TreeNode root) {
            return sum(root,0);
        }
        
        public int sum(TreeNode node,int sum){
            if(node==null){
                return 0;
            }
            if(node.left==null&&node.right==null){
                sum=sum*10+node.val;
                return sum;
            }
               return  sum(node.left,sum*10+node.val)+sum(node.right,sum*10+node.val);
        }
  • 相关阅读:
    第二月 day 2,内置函数
    第二月 day3 闭包,递归
    day4 装饰器
    第二月 day1生成器
    第一个月 总结
    day 16 迭代器
    day 15 编码
    Docker常用命令
    DRF源码刨析
    django中使用qiniu作为第三方存储
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4395029.html
Copyright © 2011-2022 走看看