zoukankan      html  css  js  c++  java
  • Path Sum leetcode java

    题目

    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.

    题解

    还是对树的操作,递归的解法:

     1     public boolean hasPathSum(TreeNode root, int sum) {
     2         if(root == null
     3             return false;
     4         
     5         sum -= root.val;
     6         if(root.left == null && root.right==null)  
     7             return sum == 0;
     8         else 
     9             return hasPathSum(root.left,sum) || hasPathSum(root.right,sum);
    10     }

    非递归的解法(Reference:http://www.programcreek.com/2013/01/leetcode-path-sum/):

     1     public boolean hasPathSum(TreeNode root, int sum) {
     2         if(root == nullreturn false;
     3  
     4         LinkedList<TreeNode> nodes = new LinkedList<TreeNode>();
     5         LinkedList<Integer> values = new LinkedList<Integer>();
     6  
     7         nodes.add(root);
     8         values.add(root.val);
     9  
    10         while(!nodes.isEmpty()){
    11             TreeNode curr = nodes.poll();
    12             int sumValue = values.poll();
    13  
    14             if(curr.left == null && curr.right == null && sumValue==sum){
    15                 return true;
    16             }
    17  
    18             if(curr.left != null){
    19                 nodes.add(curr.left);
    20                 values.add(sumValue+curr.left.val);
    21             }
    22  
    23             if(curr.right != null){
    24                 nodes.add(curr.right);
    25                 values.add(sumValue+curr.right.val);
    26             }
    27         }
    28  
    29         return false;
    30     }

  • 相关阅读:
    VS2010 Extension实践(3)——实现自定义配置
    VS2010 Extension实践(2)
    WinRT开发系列之基础概念:WinRT不是……
    [VS2010 Extension]PowerExtension.GoToDefinition
    如何通过反射调用带有ref或者out的参数的方法[迁移]
    Win7硬盘安装和移动硬盘访问出错的修复办法[迁移]
    zt. Windows Mobile开发文章收藏
    WinRT开发系列之编程语言:功能和效率
    VS2010 Extension实践
    maven创建父子工程
  • 原文地址:https://www.cnblogs.com/springfor/p/3879825.html
Copyright © 2011-2022 走看看