zoukankan      html  css  js  c++  java
  • Leetcode 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.


    解题思路:

    想了半天也没想明白,只好看答案,拍案叫绝。

    方法一: recursion. 弱点依然是recursion. 

    方法二:  use queue, 用BFS。

    Add all node to a queue and store sum value of each node to another queue. When it is a leaf node, check the stored sum value.

    For the tree above, the queue would be: 5 - 4 - 8 - 11 - 13 - 4 - 7 - 2 - 1. It will check node 13, 7, 2 and 1. This is a typical breadth first search(BFS) problem.

    记住!!!!! 


     Java code:

    方法一: recursion. 弱点依然是recursion. 

    public boolean hasPathSum(TreeNode root, int sum) {
        if (root == null)
            return false;
        if (root.val == sum && (root.left == null && root.right == null))
            return true;
     
        return hasPathSum(root.left, sum - root.val)
                || hasPathSum(root.right, sum - root.val);
    }

    方法二:  use queue, 用BFS。

    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public boolean hasPathSum(TreeNode root, int sum) {
            if(root == null) return false;
     
            LinkedList<TreeNode> nodes = new LinkedList<TreeNode>();
            LinkedList<Integer> values = new LinkedList<Integer>();
     
            nodes.add(root);
            values.add(root.val);
     
            while(!nodes.isEmpty()){
                TreeNode curr = nodes.poll();
                int sumValue = values.poll();
     
                if(curr.left == null && curr.right == null && sumValue==sum){
                    return true;
                }
     
                if(curr.left != null){
                    nodes.add(curr.left);
                    values.add(sumValue+curr.left.val);
                }
     
                if(curr.right != null){
                    nodes.add(curr.right);
                    values.add(sumValue+curr.right.val);
                }
            }
            return false;
        }
    } 

    Reference:

    1. http://www.programcreek.com/2013/01/leetcode-path-sum/

  • 相关阅读:
    一文读懂快速排序
    15道APP测试面试题分享,助攻你的面试
    APP测试之使用ADB可能遇到的错误及解决办法
    APP测试之Monkey压力测试(二)
    APP测试之Monkey压力测试(一)
    APP日志文件抓取及分析
    Linux环境安装python3
    visualvm 插件 visual gc 使用介绍
    设计模式之状态
    【深入理解JVM】:Java内存模型JMM
  • 原文地址:https://www.cnblogs.com/anne-vista/p/4815024.html
Copyright © 2011-2022 走看看