• 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.

    C++代码:

    #include<iostream>
    #include<new>
    #include<vector>
    using namespace std;
    
    //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->left==NULL&&root->right==NULL&&(sum-root->val)==0)
                return true;
            if(root->left)
                return hasPathSum(root->left,sum-root->val);
            if(root->right)
                return hasPathSum(root->right,sum-root->val);
            return false;
        }
        void createTree(TreeNode *&root)
        {
            int i;
            cin>>i;
            if(i!=0)
            {
                root=new TreeNode(i);
                if(root==NULL)
                    return;
                createTree(root->left);
                createTree(root->right);
            }
        }
    };
    int main()
    {
        Solution s;
        TreeNode *root;
        s.createTree(root);
        if(s.hasPathSum(root,6))
            cout<<"exist"<<endl;
    }

    运行结果:

  • 相关阅读:
    c语言命名规则 [转载]
    [转贴]C编译过程概述
    [转贴]漫谈C语言及如何学习C语言
    Semaphore源码分析
    如何快速转行大数据
    web前端到底怎么学?
    Code Review怎样做好
    SDK与API的理解
    分析消费者大数据
    程序员的搞笑段子
  • 原文地址:https://www.cnblogs.com/wuchanming/p/4095944.html
Copyright © 2020-2023  润新知