最低公共祖先Lowest Common Ancestor of a Binary Tree
2015-08-19 11:07
363 查看
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
解:
/**
* 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 * left=lowestCommonAncestor(root->left, p, q);
TreeNode * right=lowestCommonAncestor(root->right, p, q);
if(left && right)
return root;
return left?left:right;
}
};
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 * left=lowestCommonAncestor(root->left, p, q);
TreeNode * right=lowestCommonAncestor(root->right, p, q);
if(left && right)
return root;
return left?left:right;
}
};
相关文章推荐
- 题目:在二叉树中给出两个已知结点,求这两个结点的最低公共祖先
- 最低公共祖先问题的求解
- leetcode 235:Lowest Common Ancestor of a Binary Search Tree
- 二叉树系列4:lowest common ancestor
- PAT 1143—— Lowest Common Ancestor(二叉排序树 + 最低公共祖先)
- leetcode 139: Word Break
- 批处理命令的技巧
- JavaScript indexOf() 方法
- 关闭所有Activity和连续点击两次返回键关闭程序的方法
- windows下 IP 访问策略控制 (Windows IP安全策略控制)
- [LeetCode] Group Anagrams
- hibernate错误收集
- 嵌入式笔试
- Android:AsyncTask源码解析
- 恶补计算机基础知识 补码 进制 基本数据类型字节
- [codevs3295]落单的数
- UIButton下面添加滑动的线
- new到构造方法
- jquery ajax传递多个对象或数组到后台
- Java内部类大解析