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

    题目:给定一颗数,以及一个数sum。判断是否存在从树到叶节点的和等于sum。

    例如:

    Given the below binary tree and sum = 22,

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

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

    利用递归,和Minimum Depth类似,要考虑到叶节点才返回。很容易得到递归式子:

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        bool hasPathSum(TreeNode *root, int sum) 
        {
            if (!root) return false;
            if (!root -> left && !root -> right) return sum == root -> val;
            bool lf = false, ri = false;
            
            if (root -> left)
                lf = hasPathSum(root -> left, sum - root -> val);
            if (root -> right)
                ri = hasPathSum(root -> right, sum - root -> val);
            return lf || ri;
        }
    };

    需要注意的是当叶子节点当根节点左右子树都为空是才为叶子节点,如果有一个飞空,那么根节点自身就不是叶子节点,所以不存在只有根节点的解。

    同时记录一下非递归的解

    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;
        }
  • 相关阅读:
    go chapter 4
    go chapter 3
    ETCD相关介绍--整体概念及原理方面
    go chapter 2
    go chapter 1
    使用kubeadm搭建kubernetes1.10集群 Posted on April 14, 2018
    单用户passwd修改root密码没反应
    is not in the sudoers file解决方案
    版本更换,开始学习鸟哥的私房菜
    ubuntu 常见命令
  • 原文地址:https://www.cnblogs.com/higerzhang/p/4132797.html
Copyright © 2011-2022 走看看