首页 > 其他 > 详细

236. Lowest Common Ancestor of a Binary Tree

时间:2015-11-29 00:38:26      阅读:320      评论:0      收藏:0      [点我收藏+]

题目:

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

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.

链接: http://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/

题解:

普通二叉树求公共祖先。看过<剑指Offer>以后知道这道题应该形成一系列问题。比如是不是二叉树,是不是BST。假如是BST的话我们可以用上题的方法,二分搜索。有没有指向父节点的link,假如有指向父节点的link我们就可以用intersection of two lists的方法找到两个linked list相交的地方。 对这道题目,我们使用后续遍历来做:

  1. 定义两个辅助节点,使用后续遍历来遍历整个树
  2. 当root的值等于p或者q时,找到一个符合条件的节点,返回这个root
  3. 先遍历左子树
  4. 再遍历右子树
  5. 当left,right均找到时返回此root
  6. 只找到left时返回left
  7. 只找到right时返回right
  8. 否则返回null

Time Complexity - O(n), Space Complexity - O(n)

public class Solution {
    public static 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);      // Post order traveral
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        
        if (left != null && right != null)          // p and q in two subtrees
            return root;
        else
            return left != null ? left : right; 
    }
}

 

Reference:

 

236. Lowest Common Ancestor of a Binary Tree

原文:http://www.cnblogs.com/yrbbest/p/5003803.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!