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
- 112. Path Sum && 113. Path Sum II
- 112. Path Sum&113. Path Sum II
- 112.Path Sum
- LeetCode 112. Path Sum
- [LeetCode]112.Path Sum
- 【LeetCode】112.Path Sum
- [Leetcode] 112. Path Sum
- [leetcode] 112.Path Sum
- 112.Path Sum
- 112. Path Sum
- 112. Path Sum
- 112. Path Sum
- 112. Path Sum
- 112. Path Sum LeetCode
- 112. Path Sum
- 112. Path Sum
- 112. Path Sum
- 112. Path Sum
- Tomcat 总体结构分析
- log4j的使用
- Ajax请求回调函数没有被调用
- Android 动态绘制圆形进度条
- POJ-3292-Semi-prime H-numbers
- 112. Path Sum
- linux中的帐号密码配置文件
- C#编码规范
- SSL 之证书链
- Hibernate.cfg.xml配置文件中的hbm2ddl.auto属性
- 2.python基础学习——函数的参数
- gcc的优化 静态编译-statir
- leetCode练习(109)
- leveldb头文件的接口介绍