您的位置:首页 > 其它

236 Lowest Common Ancestor of a Binary Tree

2015-07-24 22:01 281 查看
题目链接: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.


解题思路:

前序遍历二叉树,查找p和q。

一旦找到某一节点,就将其返回,不再遍历其子树。

若某一子树遍历完后都没有找到p或q,则返回null。

每一次递归完成后,比较当前根节点的左右子树是否找到p或q。

若左右子树都找到了(p和q分别在左子树和右子树中),返回当前根节点。

若只有一个子树找到了,另一子树返回为空(p和q都在同一子树中),返回不为空的子树节点(不一定是当前根节点的子树根节点)。

若两个子树都没找到(p和q都不在该子树中),返回左子树(实则返回null)。

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public 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);
TreeNode right = lowestCommonAncestor(root.right, p, q);
return left == null ? right : right == null ? left : root;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: