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;    }};


除了递归的方法,其实还有很多种其他方法求LCS,但在代码实现上面更加复杂


比如这篇文章 http://www.verydemo.com/demo_c92_i211636.html

试求结点C和结点F的最近共同祖先

  Step1:求得二叉树的先序序列为:ABCDEFGHIJKL

  Step2:求得二叉树的后序序列为:CFEGDBJLKIHA

  Step3:分别在两个序列中找到结点C和F,并取出先序序列中在CF之前的子序列,以及后序序列中在C、F之后的子序列:

    AB DE F GHIJKL

    C FEGDBJLKIHA

    则对子序列(AB)从后向前扫描,对子序列(EGDBJLKIHA)从前向后扫描,所得到的第一个相同的结点为B故结点B为C和F的最近共同祖先。得解


0 0
原创粉丝点击