面试题50. 树中两个结点的最低公共祖先结点
题目描述:
给出一个二叉树,找到两个结点的最低公共祖先。比如下面的二叉树中,5和1的最低公共祖先就是3;
4和6的最低公共祖先就是5。
_______3______
/ \ ___5__ ___1__
/ \ / \ 6 _2 0 8
/ \ 7 4
思路:
- 如果p在左子树里,q在右子树里(或者反过来,p在右子树,q在左子树),说明当前节点为pq的最小祖先。
- 反之,说明pq要么都在左子树里,要么都在右子树里。需要分别遍历左子树和右子树。
- 用后续遍历的思想,从下往上,如果遇到了p(或q),就把p(或q)的值向上返回。以下图为例,p=3,q=9。现在要查找3和9的最近祖先。把3和9一层一层向上返回,直到6。此时6的左子树接收返回值3,右子树接收返回值9,说明6是3和9的最近祖先。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null || root == p || root == q) {
return root;
}
TreeNode left = lowestCommonAncestor(root.left, p, q); // 从root.left找p、q
TreeNode right = lowestCommonAncestor(root.right, p, q); // 从root.right找p、q
//if(left != null && right != null) return root;
// 替换成下面的语句也可以
if((left == p && right == q)||(left == q && right == p)) {
return root;
}
return (left != null) ? left : right;
}
}
参考:http://blog.csdn.net/u010429424/article/details/77650420
声明:本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。