zoukankan      html  css  js  c++  java
  • 【LeetCode】112. 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.

    Solution 1

     1 class Solution {
     2 public:
     3     bool hasPathSum(TreeNode* root, int sum) {
     4         if (!root)
     5             return false;
     6         if (!root->left && !root->right && root->val == sum)
     7             return true;
     8         return hasPathSum(root->left, sum - root->val)
     9                 || hasPathSum(root->right, sum - root->val);
    10     }
    11 };

    Solution 2

     1 class Solution {
     2 public:
     3     bool hasPathSum(TreeNode* root, int sum) {
     4         if (!root)
     5             return false;
     6         queue<TreeNode*> que;
     7         que.push(root);
     8         queue<int> qsum;
     9         qsum.push(root->val);
    10         
    11         while (!que.empty()) {
    12             TreeNode* cur = que.front();
    13             que.pop();
    14             int num = qsum.front();
    15             qsum.pop();
    16             
    17             if (!cur->left && !cur->right && num == sum) {
    18                 return true;
    19             }
    20             if (cur->left) {
    21                 que.push(cur->left);
    22                 qsum.push(cur->left->val + num);
    23             }
    24             if (cur->right) {
    25                 que.push(cur->right);
    26                 qsum.push(cur->right->val + num);
    27             }
    28         }
    29         return false;
    30     }
    31 };
  • 相关阅读:
    组件库设计
    kill 3000
    nextjs服务端渲染原理
    Web交互增强
    webpack4.0打包的时候一些技巧
    把网站部署到阿里云上的步骤
    typescript使用小结
    webpack 4.0尝鲜
    基于Quick-cocos2d-x的资源更新方案 二
    Android APK是否需要预解压
  • 原文地址:https://www.cnblogs.com/Atanisi/p/8830463.html
Copyright © 2011-2022 走看看