一大早刷了一道难度适中的题目,下面就和大家分享一下经验吧!
题目如下:
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.
Note: A leaf is a node with no children.
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.
题意分析:
给定一个二叉树和一个数(sum),请判断该树从根节点到叶子节点是否存在一条节点值相加之和为sum的路径。
方法一(递归法)
本方法的主要思路:将"sum-根节点的值"作为“新sum”,继续调用hasPathSum,通过不断递归调用,最终当遇到叶子节点的值与新“sum”的值相减为0时则返回true,否则返回false。
注:该题的递归终止条件需要多做揣摩,在判断是否为叶子节点之前,需要先判断该节点是否为空。
解题代码如下:
class Solution{
public:
bool hasPathSum(TreeNode* root, int sum){
if(!root) return false;
if(root->left == NULL && root->right == NULL) return (sum - root->val) == 0;
if(hasPathSum(root->left, sum - root->val)) return true;
if(hasPathSum(root->right, sum - root->val)) return true;
return false;
}
};
提交后的结果如下:
方法二(迭代法)
这里采用堆栈法实现的先序遍历来解决本问题。在遍历二叉树的过程中,需要将左右子结点值分别加上其父结点值然后分别赋给左右子结点,当遍历到叶子结点时,判断叶子结点的值与sum值是否相等,若相等则说明必然存在一条节点值相加之和为sum的路径故返回true,否则返回false。
解题代码如下:
class Solution{
public:
bool hasPathSum(TreeNode* root, int sum){
if(!root) return false;
stack<TreeNode* > s;
s.push(root);
while(!s.empty()){
TreeNode* temp = s.top(); s.pop();
if(!temp->left && !temp->right && temp->val == sum) return true;
if(temp->left) {temp->left->val = temp->left->val + temp->val; s.push(temp->left);}
if(temp->right) {temp->right->val = temp->right->val + temp->val; s.push(temp->right);}
}
return false;
}
};
提交后的结果如下:
日积月累,与君共进,增增小结,未完待续。