题解 | #农场牛群族谱#

农场牛群族谱

https://www.nowcoder.com/practice/7d28855a76784927b956baebeda31dc8

考察的知识点:二叉树的递归遍历;

解答方法分析:

  1. 首先,如果当前根节点为空或者当前根节点的值等于p或q的值,直接返回当前根节点的值或-1。
  2. 然后,递归调用lowestCommonAncestor函数,在根节点的左子树和右子树中查找最近公共祖先节点。
  3. 根据递归的结果进行判断,如果左子树的结果为-1,说明p和q都在右子树中,返回右子树的结果。
  4. 如果右子树的结果为-1,说明p和q都在左子树中,返回左子树的结果。
  5. 如果左子树和右子树的结果都不为-1,则说明p和q分别位于当前根节点的左右子树中,当前根节点就是最近公共祖先节点,返回当前根节点的值。

所用编程语言:C++;

完整编程代码:↓

/**
 * struct TreeNode {
 *  int val;
 *  struct TreeNode *left;
 *  struct TreeNode *right;
 *  TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param root TreeNode类
     * @param p int整型
     * @param q int整型
     * @return int整型
     */
    int lowestCommonAncestor(TreeNode* root, int p, int q) {
        if (!root || root->val == p || root->val == q) {
            return root ? root->val : -1;
        }

        int left = lowestCommonAncestor(root->left, p, q);
        int right = lowestCommonAncestor(root->right, p, q);

        if (left == -1) return right;
        if (right == -1) return left;

        return root->val;
    }
};

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-22 11:33
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
昨天 17:55
点赞 评论 收藏
分享
彧未sr:查看图片
投递牧原集团等公司10个岗位
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务