Given the root and two nodes in a Binary Tree. Find the lowest common ancestor(LCA) of the two nodes.
The lowest common ancestor is the node with largest depth which is the ancestor of both nodes.
Example
4
/ \
3 7
/ \
5 6
For 3 and 5, the LCA is 4.
For 5 and 6, the LCA is 7.
For 6 and 7, the LCA is 7.
这道题还是用分治法, 从最底下往上遍历,当找到一个所给node,向上传递node, 如果没找到就传递null。 上一层的parent会check自己的左右子树是否都有返回值,a.如果都有值那么这个node就是LCA, 向上传递这个node一直到根节点。b. 只有一个子树有值, 那么向上传递这个子树。c.若果左右都没有, 向上传递null
这道题还是用分治法, 从最底下往上遍历,当找到一个所给node,向上传递node, 如果没找到就传递null。 上一层的parent会check自己的左右子树是否都有返回值,a.如果都有值那么这个node就是LCA, 向上传递这个node一直到根节点。b. 只有一个子树有值, 那么向上传递这个子树。c.若果左右都没有, 向上传递null
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /** * @param root: The root of the binary search tree. * @param A and B: two nodes in a Binary. * @return: Return the least common ancestor(LCA) of the two nodes. */ public TreeNode lowestCommonAncestor(TreeNode root, TreeNode A, TreeNode B) { if (root == null){ return null; } if (root == A || root == B){ return root;//当找到一中一个node, 向上传递这个node } TreeNode left = lowestCommonAncestor(root.left, A, B); TreeNode right = lowestCommonAncestor(root.right, A, B); if (left != null && right != null){//check左右,如果左右分别包含两个node则这个root就是LCA, 向上传递这个node return root; } else if (left != null){//只有左边有node,向上传递此node return left; } else if (right != null){ return right; } else{//左右边都没有node 传递null return null; } } }
没有评论:
发表评论