[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;
}

运行时间

时间: 2024-09-17 22:32:25

[LeetCode]236.Lowest Common Ancestor of a Binary Tree的相关文章

[LeetCode]235.Lowest Common Ancestor of a Binary Search Tree

题目 Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. 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 h

[LeetCode] Binary Tree Level Order Traversal 二叉树层次遍历(DFS | BFS)

目录:1.Binary Tree Level Order Traversal - 二叉树层次遍历 BFS 2.Binary Tree Level Order Traversal II - 二叉树层次遍历从低往高输出 BFS 3.Maximum Depth of Binary Tree - 求二叉树的深度 DFS4.Balanced Binary Tree - 判断平衡二叉树 DFS5.Path Sum - 二叉树路径求和判断DFS 题目概述:Given a binary tree, return

[LeetCode]*105.Construct Binary Tree from Preorder and Inorder Traversal

题目 Given preorder and inorder traversal of a tree, construct the binary tree. Note: You may assume that duplicates do not exist in the tree. 思路 主要是根据前序遍历和中序遍历的特点解决这个题目. 1.确定树的根节点.树根是当前树中所有元素在前序遍历中最先出现的元素. 2.求解树的子树.找出根节点在中序遍历中的位置,根左边的所有元素就是左子树,根右边的所有元

[LeetCode]94.Binary Tree Inorder Traversal

[题目] Given a binary tree, return the inorder traversal of its nodes' values. For example: Given binary tree {1,#,2,3}, 1 \ 2 / 3 return [1,3,2]. Note: Recursive solution is trivial, could you do it iteratively? confused what "{1,#,2,3}" means? &

[LeetCode]144.Binary Tree Preorder Traversal

[题目] Given a binary tree, return the preorder traversal of its nodes' values. For example: Given binary tree {1,#,2,3}, 1 \ 2 / 3 return [1,2,3]. Note: Recursive solution is trivial, could you do it iteratively? [代码一] /*******************************

[LeetCode]199.Binary Tree Right Side View

题目 Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. For example: Given the following binary tree, 1 <- / \ 2 3 <- \ \ 5 4 <- You should return [1, 3, 4]

[LeetCode]*124.Binary Tree Maximum Path Sum

[题目] Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree. For example: Given the below binary tree, 1 / \ 2 3 Return 6. [分析]    需要考虑以上两种情况: 1 左子树或者右子树中存有最大路径和 不能和根节点形成一个路径 2 左子树 右子树 和根节点形成最大路径 [代码] /****

[LeetCode]103.Binary Tree Zigzag Level Order Traversal

[题目] Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). For example: Given binary tree {3,9,20,#,#,15,7}, 3 / \ 9 20 / \ 15 7 retur

[LeetCode]102.Binary Tree Level Order Traversal

[题目] Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). For example: Given binary tree {3,9,20,#,#,15,7}, 3 / \ 9 20 / \ 15 7 return its level order traversal as: [ [3], [9,20], [15,7