Lowest Common Ancestor of a Binary Tree
来源:互联网 发布:雅思知乎 编辑:程序博客网 时间:2024/06/05 02:48
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
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.
思路:题目给定一个二叉树和两个节点指针p和q。要求返回节点p和q的公共祖先节点,题目假定给定的节点是有效的,都是在树中的节点
(1)对于一个节点root,如果root为NULL或者root等于p或者q的话,这个时候root就是需要求出的节点
(2)如果p和q都在p的一侧且root不为p和q,则root一定不是最低的公共祖先
(3)当p和q分居在root的两侧的时候,这个时候root即为所求(递归从下到上,第一次分在左右的时候即为所求)
代码如下:
/** * 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 || 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; }};
0 0
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree(***)
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- 【每日一课】Python官方文档 5 --- 函数初步
- android Recyclerview仿京东,滚动屏幕标题栏渐变
- MFC代码修改窗口属性
- rest ( 大白话 )
- poj 1862 Stripies简单贪心
- Lowest Common Ancestor of a Binary Tree
- 《Windows via C/C++》 学习笔记
- Autocompletetextview with custom adapter and filter(Autocompletetextview 用户自定义下拉框样式)
- c++简单复数计算器
- 基于Eclipse Maven的Spring4/Spring-MVC/Hibernate4整合之三:hibernate4泛型dao的应用
- java异常处理二——try-catch-finally执行顺序
- junit测试管理类:junit test suite
- 268. Missing Number
- [leetcode] 【栈】 84. Largest Rectangle in Histogram