LeetCode-Lowest Common Ancestor of a Binary Tree 深度解析

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.

深度解析此题,因为从此题可以得出很多二叉树的知识。

1)很显然,如果每个节点有parent指针的话,一直向上找就可以找到,很方便。但是此题显然没有

2)第二种也是比较好想的,如下:

i) 如果p,q都在root的左子树,则继续在左子树上找。

ii)如果p,q都在root的右子树,则继续在右子树上找。

iii)否则,当前root就是所求,返回。

此时需要另外一个辅助方法来判断一个节点是否为另一个节点子树中的节点。

public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    	if (covers(root.left, p) && covers(root.right, q)) return lowestCommonAncestor(root.left, p, q);
    	if (covers(root.right, p) && covers(root.right, q)) return lowestCommonAncestor(root.right, p, q);
    	return root;
    }

    private boolean covers(TreeNode root, TreeNode p) {
    	if (root == p) return true;
    	if (root == null) return false;
    	return covers(root.left, p) || covers(root.right, p);
    }

代码很简介,但是不幸超时,究其原因,好多节点都重复访问了。

3)另外一个思路,先保存从root到p或q节点的路径,然后在比较两个链表,此时,需要一个辅助方法,查找从root到p,q的路径

public TreeNode lowestCommonAncestor1(TreeNode root, TreeNode p, TreeNode q) {
    	List<TreeNode> listp = getNodePath1(root, p);
    	List<TreeNode> listq = getNodePath1(root, q);

    	for (int i = 0; i < listp.size() && i < listq.size(); i++) {
    		if (listp.get(i) != listq.get(i)) {
    			return listp.get(i-1);
    		}
    	}
    	return null;
    }

    public List<TreeNode> getNodePath1(TreeNode root, TreeNode p) {
    	List<TreeNode> list = new ArrayList<TreeNode>();
    	if (p == null || !covers(root, p)) return list;
    	while (root != p) {
    		list.add(root);
    		if (covers(root.left, p)) root = root.left;
    		else if (covers(root.right, p)) root = root.right;
    	}
    	list.add(p);
    	return list;
    }

    private boolean covers(TreeNode root, TreeNode p) {
    	if (root == p) return true;
    	if (root == null) return false;
    	return covers(root.left, p) || covers(root.right, p);
    }

肯定超时,因为getNodePath跟covers的组合一样重复多次访问。

所以现在的优化目标就是能不能不重复访问的情况下,把2和3进行优化。现在可以先看之前的一道题,判断一个树是否为平衡二叉树,http://blog.csdn.net/my_jobs/article/details/47663845。可以看最后的总结,不在对树的遍历由上而下,而是由下而上,而此时只需要加一个标志位或者加个返回值。

所以对2)3)的优化就有了。

4)先看对3)的优化:

public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) {
    	List<TreeNode> listp = new ArrayList<TreeNode>();
    	List<TreeNode> listq = new ArrayList<TreeNode>();

    	getNodePath2(listp, root, p);
    	getNodePath2(listq, root, q);

    	int i = listp.size()-1;
    	int j = listq.size()-1;
    	while (i >= 0 && j >= 0) {
    		if (listp.get(i) != listq.get(j)) return listp.get(i+1);
    		i--;
    		j--;
    	}
    	return i+1 >= 0 ? listp.get(i+1) : j+1 >= 0 ? listq.get(j+1) : null;
    }
    public boolean getNodePath2(List<TreeNode> list, TreeNode root, TreeNode p) {
    	if (root == null) return false;
    	if (root == p) {
    		list.add(root);
    		return true;
    	}
    	if (getNodePath2(list, root.left, p)) {
    		list.add(root);
    		return true;
    	}
    	if (getNodePath2(list, root.right, p)) {
    		list.add(root);
    		return true;
    	}
    	return false;
    }

最后AC,此题的优化方案是当找到此节点的时候,就返回true,递归调用的上层肯定返回结果判断left,right是否在此条路径上。

5)再看对2)的优化

    public TreeNode lowestCommonAncestor3(TreeNode root, TreeNode p, TreeNode q) {
    	if (root == null || root == p || root == q) return root;
    	TreeNode left = lowestCommonAncestor1(root.left, p, q);
    	TreeNode right = lowestCommonAncestor1(root.right, p, q);
    	return left != null ? right != null ? root : left : right;
    }

代码更加精简,跟4)差不多,如果在底层的递归中发现了此节点,就向上返回,如果不为空,肯定是为当然node下。最后如果一个为空,怎说明此节点只包含p,q中的一个,如果两个都不空,则说明此节点即为所求。因为此方法是自下向上的,所以第一次遇到的节点就是所求!!!

根据上面这两种优化方案和判断一颗树是否为平衡二叉树 这三种方式,就可以看出树的这类问题的优化策略:由上向下改为由下向上!!!

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2025-01-06 15:36:11

LeetCode-Lowest Common Ancestor of a Binary Tree 深度解析的相关文章

[LeetCode] Lowest Common Ancestor of a Binary Tree 二叉树的最小共同父节点

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

leetcode——Lowest Common Ancestor of a Binary Tree

题目 Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. 思路 这一次说的是一个普通的二叉树,给出两个节点,求他们的最低公共父节点. 回想一下,当这棵二叉树是二分查找树的时候的解决方案: 二分查找树解法:http://blog.csdn.net/langduhualangdu/article/details/47426339 没错,不管是二分查找树也好还是普通二叉树也

Leetcode ——Lowest Common Ancestor of a Binary Tree

Question 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 bot

[LeetCode]Lowest Common Ancestor of a Binary Tree

第一个是普通二叉树,第二个是bst public class Solution { public 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,

88 Lowest Common Ancestor of a Binary Tree

原题网址:https://www.lintcode.com/problem/lowest-common-ancestor-of-a-binary-tree/description 描述 给定一棵二叉树,找到两个节点的最近公共父节点(LCA). 最近公共祖先是两个节点的公共的祖先节点且具有最大深度. 假设给出的两个节点都在树中存在 您在真实的面试中是否遇到过这个题?  是 样例 对于下面这棵二叉树 4 / 3 7 / 5 6 LCA(3, 5) = 4 LCA(5, 6) = 7 LCA(6, 7

leetcode - Lowest Common Ancestor of a Binary Search Tree

leetcode -  Lowest Common Ancestor of a Binary Search Tree Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined

[LeetCode][JavaScript]Lowest Common Ancestor of a Binary Tree

Lowest Common Ancestor of a Binary Tree 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 th

【LeetCode】236. Lowest Common Ancestor of a Binary Tree

Lowest Common Ancestor of a Binary Tree 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 th

LeetCode 236. Lowest Common Ancestor of a Binary Tree; 235. Lowest Common Ancestor of a Binary Search Tree

236. Lowest Common Ancestor of a Binary Tree 递归寻找p或q,如果找到,层层向上返回,知道 root 左边和右边都不为NULL:if (left!=NULL && right!=NULL) return root; 时间复杂度 O(n),空间复杂度 O(H) class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode*