LeetCode 0236.Lowest Common Ancestor of a Binary Tree【二叉树】

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

Given the following binary tree: root = [3,5,1,6,2,0,8,null,null,7,4]

Example 1:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA of nodes 5 and 1 is 3.

Example 2:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

Note:

  • All of the nodes’ values will be unique.
  • p and q are different and both values will exist in the binary tree.

题意

思路1

1) 如果当前结点 rootrootroot 等于NULL,则直接返回NULL
(2) 如果 rootrootroot 等于 ppp 或者 qqq ,那这棵树一定返回 ppp 或者 qqq
(3) 然后递归左右子树,因为是递归,使用函数后可认为左右子树已经算出结果,用 leftleftleft 和 rightrightright 表示
(4) 此时若leftleftleft为空,那最终结果只要看 rightrightright;若 rightrightright 为空,那最终结果只要看 leftleftleft
(5) 如果 leftleftleft 和 rightrightright 都非空,因为只给了 ppp 和 qqq 两个结点,都非空,说明一边一个,因此 rootrootroot 是他们的最近公共祖先
(6) 如果 leftleftleft 和 rightrightright 都为空,则返回空(其实已经包含在前面的情况中了)
时间复杂度是O(n)O(n)O(n):每个结点最多遍历一次或用主定理,空间复杂度是O(n)O(n)O(n):需要系统栈空间

代码1

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(root == NULL)
            return NULL;
        if(root == p || root == q)
            return root;
        
        TreeNode *left = lowestCommonAncestor(root->left, p, q);
        TreeNode *right = lowestCommonAncestor(root->right, p, q);
        
        if(left == NULL)  // 均在右子树
            return right;
        if(right == NULL) // 均在左子树
            return left;
        if(left && right) // 位于两侧
            return root;
        return NULL;
    }
};
原创文章 193 获赞 27 访问量 3万+

猜你喜欢

转载自blog.csdn.net/HdUIprince/article/details/105667369
今日推荐