LeetCode 236. 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.

题目思路

  • <剑指Offer>面试题68: 树中两个节点的最低公共祖先

代码 C++

/**
 * 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:
    bool findPath(TreeNode* root, TreeNode* t, vector& v){
        bool flag = false;
        
        // 在节点中加入节点
        v.push_back(root);
        // 如果找到节点,则flag=true,不再往下递归,开始返回
        if(root == t){
            flag = true;
        }
        
        // 左孩子不为NULL,且目前还没找到t,才能通过左子树递归
        if(root->left!=NULL && flag==false){
            flag = findPath(root->left, t, v);
        }
        // 右孩子不为NULL,且已经查完左子树,在左子树中没找到t,
        // 才能沿着右子树递归查找,否则在左子树中找到t,则准备返回
        if(root->right!=NULL && flag==false){
            flag = findPath(root->right, t, v);
        }
        
        // 千万注意这一点,在找到节点t之后,不能再出数组了,
        // 此时数组中保存的是根节点到t的路径(如果没有if则路径依次出栈了,程序出错)
        if(flag == false){
            v.pop_back();
        }
        
        return flag;
    }
    
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        // 如果三个节点有一个NULL,则返回NULL
        if(root == NULL || p == NULL || q == NULL){
            return NULL;
        }
        
        vector v1;
        vector v2;
        // 第一步、找到根节点到两个节点路径
        bool t1 = findPath(root, p, v1);
        bool t2 = findPath(root, q, v2);
        // t1 t2 都为 true 正面在树中找到 p q 
        if(t1==true && t2==true){
            int i=0, j=0;
            TreeNode* tt;
            // 逐步向后比较,找到最后一个相同的节点,即为输入两个节点的最低公共祖先
            while(i < v1.size() && j < v2.size() && v1[i]==v2[j]){
                tt = v1[i];
                i++;
                j++;  
            }
            return tt;
        }
        else{ // 在树中不存在 p q 
            return NULL;
        }
    }
};

总结展望

你可能感兴趣的:(LeetCode 236. Lowest Common Ancestor of a Binary Tree)