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;
        }
  • 相关阅读:
    vue-动画
    vue笔记-路由,组件
    自定义键盘信息
    自定义指令
    vue-笔记2
    轻松搭建基于 Serverless 的文档图片在线转换服务
    轻松搭建基于 SpringBoot + Vue 的 Web 商城应用
    一小时快速搭建基于阿里云容器服务-Kubernetes的Web应用
    阿里云正式推出内容平台“云栖号”:全面助力企业和个人上云决策
    云原生安全-更安全的密文管理 Vault on ACK
  • 原文地址:https://www.cnblogs.com/higerzhang/p/4132797.html
Copyright © 2011-2022 走看看