Lowest Common Ancestor of a Binary Tree
题目地址:
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/#/description
题目:
解题思路:
这道题主要就是recursion,当找到其中某个节点的时候就返回该节点。 follow up:
如果是bst的话,只需要比较root节点的值和给定的p和q的值得大小,思路同样是recursion。
代码:
follow up:
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/#/description
题目:
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.解题思路:
这道题主要就是recursion,当找到其中某个节点的时候就返回该节点。 follow up:
如果是bst的话,只需要比较root节点的值和给定的p和q的值得大小,思路同样是recursion。
代码:
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(root == null || root.val == p.val || root.val == q.val){ return root; } TreeNode left = lowestCommonAncestor(root.left, p, q); TreeNode right = lowestCommonAncestor(root.right, p, q); if(left != null && right != null){ return root; } return left != null ? left : right; }
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(root.val > p.val && root.val > q.val){ return lowestCommonAncestor(root.left, p, q); } else if(root.val < p.val && root.val < q.val){ return lowestCommonAncestor(root.right, p, q); } return root; }

Comments
Post a Comment