zoukankan      html  css  js  c++  java
  • 437. Path Sum III

    一、题目

      1、审题

      

      2、分析

        求所有的单条路径中符合和为 sum 的路径条数。结尾节点不需要为叶子节点。

    二、解答

      1、思路

        方法一、

          采用递归的方法。

          首先求从 根节点开始的路径满足和为 sum 的条数;

          其次求从 根的左孩子节点开始的路径满足和为 sum 的条数;

          最终求从 根的右孩子节点开始的路径满足和为 sum 的条数;

        public int pathSum(TreeNode root, int sum) {
            if(root == null)
                return 0;
            
            int rootLeading = pathSumFrom(root, sum);
            int leftPathLeading = pathSum(root.left, sum);
            int rightPathLeading = pathSum(root.right, sum);
            
            return rootLeading + leftPathLeading + rightPathLeading;
        }
        
        private int pathSumFrom(TreeNode root, int sum) {
    		if(root == null)
    			return 0;
    		
    		return (root.val == sum ? 1 : 0) 
    				+ pathSumFrom(root.left, sum - root.val)
    				+ pathSumFrom(root.right, sum - root.val);
    	}
    

      

  • 相关阅读:
    CheckBox循环删除代码
    最小二乘法原理
    break_VS_continue
    check the sentence &ff
    check_return
    check_FunctionAddress
    while执行两次的问题,已经解决
    CalculationWithDifferenceTpye
    SaveAboutZero
    check_negation
  • 原文地址:https://www.cnblogs.com/skillking/p/11188242.html
Copyright © 2011-2022 走看看