112. Path Sum

来源:互联网 发布:gta5购买正版淘宝网 编辑:程序博客网 时间:2024/05/19 08:44

这里写图片描述

第一种方法:深度优先遍历,递归

class Solution {public:    bool hasPathSum(TreeNode* root, int sum)     {        if(root==NULL)            return false;        else if(root->left==NULL&&root->right==NULL&&sum==root->val)            return true;        else            return hasPathSum(root->left,sum-root->val)||hasPathSum(root->right,sum-root->val);    }};

第二种方法:非递归,使用栈按层次遍历,先入栈再弹出,同时将各条路径累加和先入栈再弹出和sum比较,当走到叶子节点如果sum和累加和相等,返回true。

class Solution {public:    bool hasPathSum(TreeNode* root, int sum)     {        if(root==NULL)            return false;        stack<TreeNode *>tree;        stack<int> count;        tree.push(root);        count.push(root->val);        while(!tree.empty())        {            TreeNode *temp=tree.top();            tree.pop();            int number=count.top();            count.pop();            if(temp->left==NULL&&temp->right==NULL)            {                if(number==sum)                    return true;            }            if(temp->left)            {                tree.push(temp->left);                count.push(number+temp->left->val);            }            if(temp->right)            {                tree.push(temp->right);                count.push(number+temp->right->val);            }        }        return false;    }};
0 0
原创粉丝点击