美文网首页LeetCode By Go
[LeetCode By Go 81]235. Lowest C

[LeetCode By Go 81]235. Lowest C

作者: miltonsun | 来源:发表于2017-09-03 08:31 被阅读13次

    该题目不能用go语言写,因此使用了C语言(C++忘的更多...)。Go语言写多了,判断语句也忘了加括号,语句末尾忘了加";",一条语句的statement也加了"{}"。用C语言写几行代码也是好的,免得全忘光了。
    使用Go语言答题的时候,可以使用官方提供的测试,过滤掉一些低级语法错误,也可以非常方便的在Gogland里写测试案例进行test、debug代码,比C语言智能多了。
    通过编译、test、debug发现问题最终解决问题,总比费了半天脑子没发现一个低级错误,然后去看别人的代码要好吧。

    题目

    Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
    According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

            _______6______
          /                \ 
      ___2__             ___8__
     /      \           /      \ 
    0       4          7        9 
           / \
          3   5
    

    For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6
    . Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

    解题思路

    刚开始看的时候有点懵逼,遍历到要找的节点也不能找他父亲啊!所以还是得仔细审题,注意到给的是BST,不是普通的二叉树,肯定要从BST入手啊,想到这里就简单了(就想都是easy的题,肯定简单...)。
    因为是BST,所以对于一个树和两个目标节点,有三种情况:

    1. 两个目标节点值都小于树的根节点的值,这种情况下所求LCA肯定在树的左子树上;
    2. 两个目标节点值都大于树的根节点的值,这种情况下所求LCA肯定在树的右子树上;
    3. 两个目标节点中要么有一个节点值和树的根节点值相等,要么一个大于一个小于树的根节点值,这些情况下LCA就是树的根节点了。

    代码

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     struct TreeNode *left;
     *     struct TreeNode *right;
     * };
     */
    struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {
       if (root->val < p->val && root->val < q->val) {
            return lowestCommonAncestor(root->right, p, q);
        } else if (root->val > p->val && root->val > q->val) {
            return lowestCommonAncestor(root->left, p, q);
        } else {
            return root;
        }
    }
    

    相关文章

      网友评论

        本文标题:[LeetCode By Go 81]235. Lowest C

        本文链接:https://www.haomeiwen.com/subject/jkudjxtx.html