Lowest Common Ancestor of a Binary Tree
2015-08-17 16:17
357 查看
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).”
For example, the lowest common ancestor (LCA) of nodes
Another example is LCA of nodes
since a node can be a descendant of itself according to the LCA definition.
/**
* 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 *L = lowestCommonAncestor(root->left, p, q);
TreeNode *R = lowestCommonAncestor(root->right, p, q);
if (L && R) return root;
return L ? L : R;
}
};
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
For example, the lowest common ancestor (LCA) of nodes
5and
1is
3.
Another example is LCA of nodes
5and
4is
5,
since a node can be a descendant of itself according to the LCA definition.
/**
* 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 *L = lowestCommonAncestor(root->left, p, q);
TreeNode *R = lowestCommonAncestor(root->right, p, q);
if (L && R) return root;
return L ? L : R;
}
};
相关文章推荐
- c# 获取路径的几种方法
- Linux中brk()系统调用,sbrk(),mmap(),malloc(),calloc()的异同
- POJ 3122 Pie(二分)
- 借口也是类。也要声明一个对象来调用
- 检查一个单词是否为其他字符串的子串
- leetcode:Binary Tree Paths
- MDK如何生成bin文件?
- 地图分幅概述
- MySQL的时间进位问题
- 39 网络相关函数(七)——live555源码阅读(四)网络
- 受不了熱浪的刺激
- POJ 1679 The Unique MST(判断最小生成树_Kruskal)
- java web前端学习网站
- CentOS 7安装Nginx
- Spring学习笔记(七):IOC控制反转
- 关于董事会绩效评估的思考
- 数组的内存结构
- [LeetCode] Single Number III
- 利用Python在堡垒机模式下批量管理后端nginx服务器
- 【快速幂】【扩展欧几里德】【BSGS】【SDOI 2011】【bzoj 2242】计算器