码迷,mamicode.com
首页 > 其他好文 > 详细

[Leetcode] Path Sum路径和

时间:2017-06-10 22:30:32      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:val   equals   pre   递归   for   target   while   empty   定义   

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 andsum = 22,

              5
             /             4   8
           /   /           11  13  4
         /  \              7    2      1

return true, as there exist a root-to-leaf path5->4->11->2which sum is 22.

题意:给定一个数,判断是否存在一条从根节点到叶节点的路径,使得,路径上节点所对应的值得和等于这个数。

方法一:使用递归解法。

针对一条路径:通过用sum减去当前节点的值,直到最后看最后叶节点的值是否等于sum剩余的值来判断是否存在。

一、终止条件,1)初始时,root为空,返回false;最后,root->left、root->right不存在时,依旧不等于sum,也返回false;

       2)当达到叶节点时,当前节点的值等于sum剩余值,返回true;

二、递归表达式,对一个节点,左、右子树中有一条路径满足条件就行。

/**
 * 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==NULL)  return false;

        if(root->left==NULL&&root->right==NULL&&root->val==sum)
            return true;

        return hasPathSum(root->left,sum-root->val)||hasPathSum(root->right,sum-root->val) ;   
    }
};

 方法二:利用后续遍历的思想

减值的过程类似后续遍历中的方法二。具体过程:先沿左子树的左孩子不停的将左孩子重复入栈,并计算和栈中节点的和,直到左孩子为空,若为叶节点且val=sum,则返回true,否则再转向右孩子。定义变量pre防止重复的访问右子树,每次出栈时,特别要注意的是,要将cur赋值为NULL这样可以跳过while循环,避免重复访问左孩子。具体代码如下:

/**
 * 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) 
    {
        stack<TreeNode *> stk;
        TreeNode *pre=NULL;
        TreeNode *cur=root;
        int temVal=0;

        while(cur|| !stk.empty())
        {
            while(cur)
            {
                stk.push(cur);
                temVal+=cur->val;
                cur=cur->left;
            }
            cur=stk.top();
            if(cur->left==NULL&&cur->right==NULL&&temVal==sum)
                return true;
            if(cur->right&&cur->right !=pre)
                cur=cur->right;
            else
            {
                stk.pop();
                temVal-=cur->val;
                pre=cur;
                cur=NULL;
            }

        } 
        return false;
    }
};

 

[Leetcode] Path Sum路径和

标签:val   equals   pre   递归   for   target   while   empty   定义   

原文地址:http://www.cnblogs.com/love-yh/p/6980002.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!