[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 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).”


      3
   /     \
  5       1
/   \    /  \
6   2   0    8
   /  \
  7    4


Another example is LCA of nodes 5 and 4 is 5,  
since a node can be a descendant of itself according to the LCA definition.

代码

/*---------------------------------------
*   日期:2015-07-13
*   作者:SJF0115
*   题目: 236.Lowest Common Ancestor of a Binary Tree
*   网址:https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
*   结果:AC
*   来源:LeetCode
*   博客:
-----------------------------------------*/
#include <iostream>
#include <vector>
using namespace std;

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 == nullptr || p == nullptr || q == nullptr){
            return nullptr;
        }//if
        vector<TreeNode*> path1;
        bool isFind = Path(root,p,path1);
        // 没有P节点
        if(!isFind){
            return nullptr;
        }//if
        vector<TreeNode*> path2;
        isFind = Path(root,q,path2);
        if(!isFind){
            return nullptr;
        }//if
        int size1 = path1.size();
        int size2 = path2.size();
        // 求最近祖先
        TreeNode* node = nullptr;
        for(int i = 0,j = 0;i <= size1 && j <= size2;++i,++j){
            if((i == size1 || j == size2) || path1[i] != path2[j]){
                node = path1[i-1];
                break;
            }//if
        }//for
        return node;
    }
private:
    // 从根节点到node节点的路径
    bool Path (TreeNode* root,TreeNode* node,vector<TreeNode*> &path) {
        path.push_back(root);
        if(root == node) {
            return true;
        }//if
        bool isExits = false;
        // 左子树
        if(root->left) {
            isExits = Path(root->left,node,path);
        }//if
        // 右子树
        if(!isExits && root->right) {
            isExits = Path(root->right,node,path);
        }//if
        if(!isExits) {
            path.pop_back();
        }//if
        return isExits;
    }
};

int main(){
    Solution s;
    TreeNode* root = new TreeNode(3);
    TreeNode* node1 = new TreeNode(0);
    TreeNode* node2 = new TreeNode(1);
    TreeNode* node3 = new TreeNode(2);
    TreeNode* node4 = new TreeNode(4);
    TreeNode* node5 = new TreeNode(5);
    TreeNode* node6 = new TreeNode(6);
    TreeNode* node7 = new TreeNode(7);
    TreeNode* node8 = new TreeNode(8);
    root->left = node5;
    root->right = node2;
    node5->left = node6;
    node5->right = node3;
    node3->left = node7;
    node3->right = node4;
    node2->left = node1;
    node2->right = node8;
    TreeNode* node = s.lowestCommonAncestor(root,node7,node1);
    if(node != nullptr){
        cout<<node->val<<endl;
    }//if
    else{
        cout<<"nullptr"<<endl;
    }//else
    return 0;
}

运行时间

这里写图片描述

目录
相关文章
|
Java
Leetcode 114. Flatten Binary Tree to Linked List
思路也很简单,先把root的左子树(如有)变成单链表 leftlinkedlist,把root的右子树(如有)变成单链表 rightlinkedlist,再把root的右节点变成leftlikedlist,再把rightlinkedlist接到leftlinkedlist后面,代码如下。
134 1
Leetcode Minimum Depth of Binary Tree (面试题推荐)
计算树的最小深度 很简单的一道题,只需要遍历一次树,到叶子节点的时候计算一下深度和当前最小深度比较,保存最小值就行。 我在这用了一个全局变量 mindepth。总感觉我这代码写的不够简练,求更精简的方法。
146 0
Leetcode Binary Tree Postorder Traversal(面试题推荐)
非递后续归遍历二叉树,肯定得用到栈。先序遍历很好写,但后续遍历就不是那么容易了。 只需要设置个指针pre,指向最后输出的那个节点就行了,只要判断cur指针指向的是上次输出节点的父节点,且cur无其他未遍历的节点,这个时候就把cur节点输出即可,然后更改pre。原理是要遍历当前节点,其所有子节点都必须遍历完,因为肯定是先左后右,所以只需一个指针保持前一次输出的结果即可。
134 0
Leetcode 236. Lowest Common Ancestor of a Binary Tree
根据LCA的定义,二叉树中最小公共祖先就是两个节点p和q最近的共同祖先节点,LCA的定义没什么好解释的,主要是这道题的解法。
146 0
Leetcode 623. Add One Row to Tree
题目很简单,在树的第d层加一层,值为v。递归增加一层就好了。代码如下
127 0
LeetCode contest 190 5418. 二叉树中的伪回文路径 Pseudo-Palindromic Paths in a Binary Tree
LeetCode contest 190 5418. 二叉树中的伪回文路径 Pseudo-Palindromic Paths in a Binary Tree
|
算法 Python
LeetCode 108. 将有序数组转换为二叉搜索树 Convert Sorted Array to Binary Search Tree
LeetCode 108. 将有序数组转换为二叉搜索树 Convert Sorted Array to Binary Search Tree
|
Unix Shell Linux
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
本文提供了几个Linux shell脚本编程问题的解决方案,包括转置文件内容、统计词频、验证有效电话号码和提取文件的第十行,每个问题都给出了至少一种实现方法。
259 6
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
|
Python
【Leetcode刷题Python】剑指 Offer 32 - III. 从上到下打印二叉树 III
本文介绍了两种Python实现方法,用于按照之字形顺序打印二叉树的层次遍历结果,实现了在奇数层正序、偶数层反序打印节点的功能。
169 6
|
搜索推荐 索引 Python
【Leetcode刷题Python】牛客. 数组中未出现的最小正整数
本文介绍了牛客网题目"数组中未出现的最小正整数"的解法,提供了一种满足O(n)时间复杂度和O(1)空间复杂度要求的原地排序算法,并给出了Python实现代码。
370 2

热门文章

最新文章