zoukankan      html  css  js  c++  java
  • Path Sum

    简单递归,但代码简洁性有待提高

    我的代码

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     struct TreeNode *left;
     *     struct TreeNode *right;
      * };
     */
    bool hasPathSum(struct TreeNode *root, int sum) {
        if(root == NULL) return false;
        if(root->left == NULL && root->right == NULL){
            if(sum == root->val) return true;
            return false;
        }
        bool ok = false;
        ok = hasPathSum(root->left,sum-root->val);
        if(ok == true) return true;
        ok = hasPathSum(root->right,sum-root->val);
        return ok;
    }

    别人的比较简洁的代码

    class Solution {
    public:
        bool hasPathSum(TreeNode *root, int sum) {
            if(!root) return false;
            if(!root->left && !root->right)
                return root->val == sum;
            return hasPathSum(root->left,sum-root->val) || hasPathSum(root->right,sum-root->val);
        }
    };
  • 相关阅读:
    从Python到Web开发
    源码安装缺少configure文件
    5
    4
    3
    2
    42
    1
    18
    41
  • 原文地址:https://www.cnblogs.com/llei1573/p/4323471.html
Copyright © 2011-2022 走看看