Chinaunix首页 | 论坛 | 博客
  • 博客访问: 121012
  • 博文数量: 53
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 620
  • 用 户 组: 普通用户
  • 注册时间: 2014-08-24 16:22
文章存档

2014年(53)

我的朋友

分类: C/C++

2014-12-13 18:20:56

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.


Show Tags
Have you met this question in a real interview?

这个题关键在于如何在递归中计算遍历的节点的和,一个技巧就是入口处加,出口处减,当然还有的诀窍是传值传递参数

首先看用全局变量或者引用传递的方法,用时20ms

  1. int num=0;
  2. bool hasPathSum(TreeNode *root, int sum){
  3.     if(root==NULL)
  4.         return false;
  5.     num+=root->val;
  6.     if(root->left==NULL && root->right==NULL){
  7.         if(num==sum){
  8.             num-=root->val;
  9.             return true;
  10.         }
  11.         else{
  12.             num-=root->val;
  13.             return false;
  14.         }
  15.     }
  16.     bool result= hasPathSum(root->left,sum)||hasPathSum(root->right,sum);
  17.     num-=root->val;
  18.     return result;
  19. }
然后看值传递的方式:耗时80ms,明显慢一些,和传了三个参数关系不大,因为去掉成两个参数之后还是76ms

  1. bool f(TreeNode *root, int& sum, int num){
  2.     if(root==NULL)
  3.         return false;
  4.     num+=root->val;
  5.     if(root->left==NULL && root->right==NULL){
  6.         if(num==sum){
  7.             return true;
  8.         }
  9.         else{
  10.             return false;
  11.         }
  12.     }
  13.     return f(root->left,sum,num)||f(root->right,sum,num);
  14. }
  15. bool hasPathSum(TreeNode *root, int sum){
  16.     return f(root,sum,0);
  17. }





阅读(1364) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~