leetcode 每日一题 236. Lowest Common Ancestor of a Binary Tree
来源:互联网 发布:ubuntu 时区 编辑:程序博客网 时间:2024/06/05 02:41
比昨天的搜索二叉树来说更难一点点 不过用递归的方法还是很便捷。
看了思路之后自己写了一下,其实还是有很多地方需要注意的,比如注释中的
首先给出的是两个节点,因此要用节点和root比较,而不是用节点的值比较
其次,定义了lft和rgt两个递归的结果之后,判断时要用lft不为空做判断,一开始我用的是为空,其实这样就缺少了条件,因为并不知道rgt是不是为空?
要用if else语句,用很多if的叠加容易漏掉条件。
最后,return时需要直接return lft或者rgt的结果,不要再次return循环函数了,会出现超时的情况····(算一遍还不够还要算几遍?)
class Solution {public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { TreeNode* res=root; if(res==NULL) return res; if(res==p||res==q) return res; //根节点即是LCS 不要用val做比较,要用节点比较,因为给的就是节点 TreeNode* lft=lowestCommonAncestor(res->left,p,q); TreeNode* rgt=lowestCommonAncestor(res->right,p,q); if(lft!=NULL&&rgt!=NULL) return res; else if(lft!=NULL) return lft; //这里要用lft不为空作为判断,防止有漏洞 else return rgt; }};
上面的我的代码比较清晰,discuss中有更加简洁的代码,4行
https://leetcode.com/discuss/82443/concise-4-line-c
class Solution {public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if (!root || root == p || root == q) return root; TreeNode* l = lowestCommonAncestor(root->left, p, q); TreeNode* r = lowestCommonAncestor(root->right, p, q); return l && r ? root : l ? l : r; }};
比如这篇文章 http://www.verydemo.com/demo_c92_i211636.html
试求结点C和结点F的最近共同祖先。
Step1:求得二叉树的先序序列为:ABCDEFGHIJKL
Step2:求得二叉树的后序序列为:CFEGDBJLKIHA
Step3:分别在两个序列中找到结点C和F,并取出先序序列中在C、F之前的子序列,以及后序序列中在C、F之后的子序列:
AB C DE F GHIJKL
C FEGDBJLKIHA
则对子序列(AB)从后向前扫描,对子序列(EGDBJLKIHA)从前向后扫描,所得到的第一个相同的结点为B。故结点B为C和F的最近共同祖先。得解。 0 0
- leetcode 每日一题 236. Lowest Common Ancestor of a Binary Tree
- 【leetcode每日一题】235.Lowest Common Ancestor of a Binary Search Tree
- leetcode 每日一题 235. Lowest Common Ancestor of a Binary Search Tree
- leetcode:235 Lowest Common Ancestor of a Binary Search Tree-每日编程第十二题
- [leetcode] 236.Lowest Common Ancestor of a Binary Tree
- [LeetCode]236.Lowest Common Ancestor of a Binary Tree
- [leetcode] 236.Lowest Common Ancestor of a Binary Tree
- [LeetCode]236. Lowest Common Ancestor of a Binary Tree
- 236. Lowest Common Ancestor of a Binary Tree LeetCode
- [leetcode] 236. Lowest Common Ancestor of a Binary Tree
- leetcode 236. Lowest Common Ancestor of a Binary Tree
- LeetCode-236.Lowest Common Ancestor of a Binary Tree
- LeetCode 236. Lowest Common Ancestor of a Binary Tree
- LeetCode *** 236. Lowest Common Ancestor of a Binary Tree
- leetcode.236. Lowest Common Ancestor of a Binary Tree
- LeetCode - 236. Lowest Common Ancestor of a Binary Tree
- LeetCode 236. Lowest Common Ancestor of a Binary Tree
- [LeetCode] 236. Lowest Common Ancestor of a Binary Tree
- hdu 1978 How many ways (记忆化搜索)
- git am PATCH 失败的处理方法
- cocos动作使用示例(3)
- 实现前端md5加密与记住用户名密码功能
- 代理模式
- leetcode 每日一题 236. Lowest Common Ancestor of a Binary Tree
- Linux内核源码阅读以及工具
- 每天学点Excel技巧-Day1
- Mavlink地面站编写之一--协议分析
- 正则表达式课堂笔记
- 用SMT对大数据 过滤
- mxnet代码剖析之--mshadow篇
- 使用MAC的一些小知识
- iOS性能优化之内存管理:Analyze、Leaks、Allocations的使用和案例代码