版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ghscarecrow/article/details/86570462
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 p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
Given the following binary tree: root = [3,5,1,6,2,0,8,null,null,7,4]
Example 1:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 Output: 3 Explanation: The LCA of nodes5
and1
is3.
Example 2:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 Output: 5 Explanation: The LCA of nodes5
and4
is5
, since a node can be a descendant of itself according to the LCA definition.
Note:
- All of the nodes' values will be unique.
- p and q are different and both values will exist in the binary tree.
思考:这是一道二叉树搜索最低公共祖先结点的题,按照以往的经验,我们知道,树的问题一般可以采用递归的方式来进行编程。那么,是采用自顶向下还是自底向上呢?由于需要找最低的公共祖先结点,所以应该采用自底向上的递归方式进行编程。而且由题意我们容易知道给出的二叉树数据结点都是唯一的,所以,当我们在左子树找到p结点,而在右子树找到q结点时,我们便可以找到当前结点为p,q结点的最低公共祖先结点(因为是自底向上递归的)这里还需考虑到,如果p(q)为q(p)的祖先结点,那么p(q)就是p,q的祖先结点了。
实现代码如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private TreeNode ans;
public Solution(){
this.ans = null;
}
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
//TreeNode ans = null;
traverse(root,p,q);
return ans;
}
public boolean traverse(TreeNode currentNode,TreeNode p,TreeNode q){
if(currentNode == null){
return false;
}
int left = this.traverse(currentNode.left,p,q)? 1:0;
int right = this.traverse(currentNode.right,p,q)? 1:0;
int mid = (currentNode==p || currentNode==q)? 1:0;
if(left + right +mid >= 2){
ans = currentNode;
}
return (mid + left + right >0);
}
}