第八周LeetCode
来源:互联网 发布:阿里弹性云 编辑:程序博客网 时间:2024/06/08 13:28
题目
难度 Easy
Path Sum
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.
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
实现思路
题目要找一条从根节点到叶子节点的路径,使得这条路径长度等于输入的长度,如果不存在返回0否则返回1。由于要找的是从根到叶子节点的路径,可以先搜索根节点,然后分别对根节点的左子节点和右子节点做深度优先搜索,若在左子树中找到路径就返回true,否则在右子树中找,找到就返回true否则返回false。由于输入是一个二叉树,此做法就相当于对二叉树根节点进行先序遍历。算法的时间复杂度为O(h),h为二叉树高度。
实现代码
void preOrder(TreeNode* root, int &count, const int sum, bool &flag) { count += root->val; if (count == sum && root->left == NULL && root->right == NULL) { flag = true; } //如果找到就返回 if (flag) { return; } if (root->left) { preOrder(root->left, count, sum, flag); } //如果在左子树中找到就返回 if (flag) { return; } //如果找不到就回溯 if (root->left) count -= root->left->val; if (root->right) { preOrder(root->right, count, sum, flag); } //如果找不到就回溯 if (root->right) count -= root->right->val;}bool hasPathSum(TreeNode* root, int sum) { int count = 0; if (root) count = root->val; else return false; //只有根节点,且输入的长度即为根节点的权值 if (count == sum && root->left == NULL && root->right == NULL) return true; bool flag = false; if (root->left) { preOrder(root->left, count, sum,flag); } count = root->val; if (!flag && root->right) { preOrder(root->right, count, sum,flag); } return flag;}
阅读全文
0 0
- leetcode-python 第八周
- leetcode-第八周
- 第八周leetcode题
- 第八周LeetCode
- 第八周LeetCode
- [leetcode]第八周作业
- LeetCode题解 第八周
- leetcode第八周解题总结
- 第八周LeetCode算法题两道
- Leetcode 算法习题 第八周
- 第八周:[leetcode] 228. Summary Ranges
- 第八周:[leetCode] 91. Decode Ways
- 第八周:[Leetcode]5. Longest Palindromic Substring
- 第八周:[Leetcode]516. Longest Palindromic Subsequence
- 第八周:[Leetcode]300. Longest Increasing Subsequence
- leetcode【第八周】链表划分
- Leetcode算法课程第八周(补)
- 第八周:[leetcode] 209. Minimum Size Subarray Sum
- Java中Properties类的操作
- ERROR:ORA-01033: ORACLE initialization or shutdown in progess
- 蚂蚁金服加价36%并购速汇金,但美方监管障碍依然存在
- 洛谷U13669 一道好题——和谐的村庄
- 传统到soa构架的演变
- 第八周LeetCode
- poj 2886
- 通过setxxx()和getxxx()方法对类中的私有成员变量进行赋值和访问
- JavaScript的typeof运算符的可能结果
- 【C++心路历程41】【体检】【贪心】【思路题】
- linux命令--tree显示文件目录结构
- Hibernate 半深入懒加载与懒加载代理类
- NOIP2016 换教室 期望DP
- 谷歌的天敌竟然是亚马逊?从开放 7-Mic 阵列授权说起 | 洞见