zoukankan      html  css  js  c++  java
  • [Leetcode] Path Sum

    Path Sum 题解

    题目来源:https://leetcode.com/problems/path-sum/description/


    Description

    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.

    Example

    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.

    Solution

    class Solution {
    public:
        bool hasPathSum(TreeNode* root, int sum) {
            if (!root)
                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));
        }
    };
    

    解题描述

    这道题题意是对给出的数字sum,检索二叉树上根到叶子节点的路径,求路径上节点数据之和能否等于sum。上面给出的是递归实现DFS的解法,下面给出的是BFS的解法:

    class Solution {
    private:
        struct Task {
            TreeNode *node;
            int sum;
            Task(TreeNode* n, int s) : node(n), sum(s) {}
        };
    public:
        bool hasPathSum(TreeNode* root, int sum) {
            if (!root)
                return false;
            queue<Task> q;
            q.push(Task(root, sum));
            while (!q.empty()) {
                Task task = q.front();
                q.pop();
                TreeNode *node = task.node;
                if (node -> left == NULL && node -> right == NULL &&
                        node -> val == task.sum)
                    return true;
                if (node -> left) {
                    q.push(Task(node -> left, task.sum - (node -> val)));
                }
                if (node -> right) {
                    q.push(Task(node -> right, task.sum - (node -> val)));
                }
            }
            return false;
        }
    };
    
  • 相关阅读:
    Linux常用命令
    全文搜索服务器solr
    非关系型数据库之redis
    springMVC流程
    浅谈spring框架的控制反转和依赖注入
    Java基础之数组
    Java基础之方法
    跨域访问接口,传递参数
    Centos 6无法使用yum
    内网穿透工具:钉钉HTTP内网穿透使用与讲解
  • 原文地址:https://www.cnblogs.com/yanhewu/p/8406221.html
Copyright © 2011-2022 走看看