【Leetcode】Lowest Common Ancestor of a Binary Tree

题目链接:https://leetcode.com/problems/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.

思路:

分两种情况,一、当两结点是祖孙关系,即在树中是在一条从上到下的路径的时候;二、当两结点在某结点左右子树中,即为兄弟关系的时候。

算法:

	TreeNode target = null;
	public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
		// 如果p/q是祖孙关系,即在一条由上到下的路径上
		if (findNodeRec(p, q)) {
			return p;
		}
		if (findNodeRec(q, p)) {
			return q;
		}
		// ===如果p/q不是祖孙关系,而是类似与兄弟关系,即分布在root两边
		if (findNodeRec(root.left, p)) {
			if (findNodeRec(root.right, q)) {
				target = root; // 如果两节点在root的左右子树上,则root就是所求的最低公共祖先
			} else { // 如果n1、n2都在树的左子树
				if (root.left != null)
					lowestCommonAncestor(root.left, p, q); // 判断左子树哪个节点是最低公共祖先
			}
		} else {
			if (findNodeRec(root.left, q)) {
				target = root;
			} else {
				if (root.right != null)
					lowestCommonAncestor(root.right, p, q);
			}
		}
		return target;
	}

	/**
	 *判断t是不是root子孙 
	 */
	public boolean findNodeRec(TreeNode root, TreeNode t) { 
		if (root == null || t == null)
			return false;
		if (root == t)
			return true;
		boolean left = findNodeRec(root.left, t); // 先在左字树中找
		boolean right = findNodeRec(root.right, t);
		return left || right;
	}


你可能感兴趣的:(【Leetcode】Lowest Common Ancestor of a Binary Tree)