zoukankan      html  css  js  c++  java
  • 112. Path Sum二叉树路径和

    [抄题]:

    Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

    For example:
    Given the below binary tree and sum = 22,

                  5
                 / 
                4   8
               /   / 
              11  13  4
             /        
            7    2      1
    

    return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

     [暴力解法]:

    时间分析:

    空间分析:

    [奇葩输出条件]:

    字符串中间还要加符号,头一次见

    [奇葩corner case]:

    两端都是空,只有root一个点也是能求和的,第一次见。下次二叉树求和的时候只要有点就能加

    [思维问题]:

    不知道怎么利用sum:变成参数即可

    [一句话思路]:

    还是没有汇总的traverse,把sum参与进来,把sum参数化变成一个参数就行了

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

      [五分钟肉眼debug的结果]:

    [总结]:

    [复杂度]:Time complexity: O(n) Space complexity: O(n)

    [英文数据结构或算法,为什么不用别的数据结构或算法]:

    [关键模板化代码]:

    [其他解法]:

    [Follow Up]:

    [LC给出的题目变变变]:

    path sum后续系列

     [代码风格] :

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public boolean hasPathSum(TreeNode root, int sum) {
            //root is null
            if (root == null) {
                return false;
            }
            //only root is not null
            if (root.left == null && root.right == null) {
                return root.val == sum;
            }
            //remaning sum in left or sum in right
            return (hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val));
        }
    }
    View Code
  • 相关阅读:
    桥梁模式
    原型模式
    css backgroundposition
    eclipse配置了maven,项目报错
    SQL 练习题目
    Springmvc + Ibatis 搭建 点餐系统
    Delphi 性能优化工具
    Delphi的接口陷阱
    delphi 内存管理,定期释放
    Delphi制作数据感知控件之浮想联翩
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8543452.html
Copyright © 2011-2022 走看看