菜鸡刷Leetcode之236. Lowest Common Ancestor of a Binary Tree Medium

时间:2019-09-09
本文章向大家介绍菜鸡刷Leetcode之236. Lowest Common Ancestor of a Binary Tree Medium,主要包括菜鸡刷Leetcode之236. Lowest Common Ancestor of a Binary Tree Medium使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
236. Lowest Common Ancestor of a Binary Tree Medium

https://leetcode.com/problems/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.

分析:

首先,树的问题,往往涉及递归,之所以涉及递归是因为每一棵树都是由相同结构的多个子树构成。本题可以利用递归的方式,相当于从叶子节点开始,递归地返回如下信息:当前树(或子树)同时包含p和q,则函数返回的结果就是它们的最低公共祖先。如果它们其中之一在子树当中,则结果是它们中的一个。如果它们都不在子树里,则结果返回NULL。

class Solution {
public:
    TreeNode * lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        // 虽然下面两个if可以写到一起,但所表达的意思是不一样的
        if (root == nullptr) {
            return nullptr;
        }
        if (p == root || q == root) {
            return root;
        }
        TreeNode* left = lowestCommonAncestor(root->left, p, q);
        TreeNode* right = lowestCommonAncestor(root->right, p, q);
        if (left == nullptr) {  // 如果有一个分支为空,另一个不为空,则返回不为空的节点
            return right;
        }
        else if (right == nullptr) {
            return left;
        }
        else  // 如果两个都不为空,则返回二者当前最低祖先节点
            return root;
    }
};

总结:

书上对这道题的做法麻烦了。首先书上并不是二叉树,而是一颗普通树,所以next存在一个vector里。
其次,书上的做法是先找到p和q两条路径,从根节点出发到p和q分别构成两条链表;
最后,寻找这两条链表的第一个分叉的地方。

注:

如果本题的树是二叉搜索树或者有指向父节点的指针,则思路能更加简单。

原文地址:https://www.cnblogs.com/Flash-ylf/p/11494780.html