235.236. Lowest Common Ancestor of a Binary (Search) Tree -- 最近公共祖先
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 has both v and w as descendants (where we allow a node to be a descendant of itself).”
_______6______
/ \
___2__ ___8__
/ \ / \
0 _4 7 9
/ \
3 5
For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
while(root) {
if (p->val > root->val && q->val > root->val) {
root = root->right;
continue;
}
if (p->val < root->val && q->val < root->val) {
root = root->left;
continue;
}
return root;
}
return NULL;
}
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
For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. 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.
(1)一次递归找两个节点
TreeNode* lowestCommonAncestor02(TreeNode* root, TreeNode* p, TreeNode* q) {
//return if found or not found, return NULL if not found
if (root==NULL || root == p || root == q) return root;
//find the LCA in left tree
TreeNode* left = lowestCommonAncestor02(root->left, p, q);
//find the LCA in right tree
TreeNode* right = lowestCommonAncestor02(root->right, p, q);
//left==NULL means both `p` and `q` are not found in left tree.
if (left==NULL) return right;
//right==NULL means both `p` and `q` are not found in right tree.
if (right==NULL) return left;
// left!=NULL && right !=NULL, which means `p` & `q` are seperated in left and right tree.
return root;
}
(2)分别记录根节点到所求节点的先序遍历路径,返回路径中最后一个相同的节点
bool findPath(TreeNode* root, TreeNode* p, vector<TreeNode*>& path) {
if (root==NULL) return false;
if (root == p) {
path.push_back(p);
return true;
}
path.push_back(root);
if (findPath(root->left, p, path)) return true;
if (findPath(root->right, p, path)) return true;
path.pop_back();
return false;
}
//Ordinary way, find the path and comapre the path.
TreeNode* lowestCommonAncestor01(TreeNode* root, TreeNode* p, TreeNode* q) {
vector<TreeNode*> path1, path2;
if (!findPath(root, p, path1)) return NULL;
if (!findPath(root, q, path2)) return NULL;
int len = path1.size() < path2.size() ? path1.size() : path2.size();
TreeNode* result = root;
for(int i=; i<len; i++) {
if (path1[i] != path2[i]) {
return result;
}
result = path1[i];
}
return result;
}
235.236. Lowest Common Ancestor of a Binary (Search) 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 BS ...
- LeetCode (236):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 BS ...
- leetcode 235. Lowest Common Ancestor of a Binary Search Tree 236. Lowest Common Ancestor of a Binary Tree
https://www.cnblogs.com/grandyang/p/4641968.html http://www.cnblogs.com/grandyang/p/4640572.html 利用二 ...
- 【LeetCode】235. Lowest Common Ancestor of a Binary Search Tree (2 solutions)
Lowest Common Ancestor of a Binary Search Tree Given a binary search tree (BST), find the lowest com ...
- LeetCode_235. Lowest Common Ancestor of a Binary Search Tree
235. Lowest Common Ancestor of a Binary Search Tree Easy Given a binary search tree (BST), find the ...
- [geeksforgeeks] Lowest Common Ancestor in a Binary Search Tree.
http://www.geeksforgeeks.org/lowest-common-ancestor-in-a-binary-search-tree/ Lowest Common Ancestor ...
- leetcode面试准备:Lowest Common Ancestor of a Binary Search Tree & Binary Tree
leetcode面试准备:Lowest Common Ancestor of a Binary Search Tree & Binary Tree 1 题目 Binary Search Tre ...
- Lowest Common Ancestor of a Binary Search Tree、Lowest Common Ancestor of a Binary Search Tree
1.Lowest Common Ancestor of a Binary Search Tree Total Accepted: 42225 Total Submissions: 111243 Dif ...
- [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 BS ...
随机推荐
- FNV hash算法
原文:https://blog.csdn.net/u013137970/article/details/79020095 FNV算法简介FNV算法属于非密码学哈希函数,它最初由Glenn Fowler ...
- struts2的琐碎知识点
servlet:void init(ServletConfig cfg):// 读取servlet的配置参数void service(ServletRequest request, ServletRe ...
- Linux服务器报错too many open files错误解决方案
1.本质解决方案按照oracle的安装脚本中以下几项文件进行相应配置: cp /etc/security/limits.conf /etc/security/limits.conf.bak echo ...
- 修改mysql的字符集和默认存储引擎
转自:http://blog.csdn.net/wyzxg/article/details/8779682 author:skatetime:2012/05/18 修改mysql的字符集和默认存储引擎 ...
- c primer plus(五版)编程练习-第七章编程练习
1.编写一个程序.该程序读取输入直到遇到#字符,然后报告读取的空格数目.读取的换行符数目以及读取的所有其他字符数目. #include<stdio.h> #include<ctype ...
- PHP对象转数组
Solution json_decode( json_encode( $obj ), true ): But why?You should have a look at the function na ...
- 2018-2019 Всероссийская командная олимпиада школьников по программированию, интернет-тур + отборы регионов (ВКОШП 18, интернет-тур) Solution
A: 水. #include<bits/stdc++.h> using namespace std; typedef long long ll; const ll INFLL = 0x3f ...
- git使用多个SSH公钥信息
常常在开发环境存在多个git库,比如官方的github.公司搭建的gitlab.自己的私人库等等多个git库,为了方便使用,git需要配置多个SSH公钥信息. 在centos7.5下,进入用户目录,以 ...
- 常用php操作redis命令整理(五)ZSET类型
ZADD 向有序集合插入一个元素,元素关联一个数值,插入成功返回1,同时集合元素不可以重复, 如果元素已经存在返回 0 <?php var_dump($redis->zadd(,'A')) ...
- bzoj1600 [Usaco2008 Oct]建造栅栏(递推)
Description 勤奋的Farmer John想要建造一个四面的栅栏来关住牛们.他有一块长为n(4<=n<=2500)的木板,他想把这块本板 切成4块.这四块小木板可以是任何一个长度 ...