面试题50. 树中两个结点的最低公共祖先结点

来源:互联网 发布:安庆四中信息编程班 编辑:程序博客网 时间:2024/06/06 05:56

面试题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

这里写图片描述

阅读全文
0 0