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 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).”
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.
Code
/**
* 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) return null;
List<TreeNode> pathP = new ArrayList<>();
List<TreeNode> pathQ = new ArrayList<>();
pathP.add(root);
pathQ.add(root);
getPath(root, p, pathP);
getPath(root, q, pathQ);
TreeNode result = null;
for (int i = 0; i < pathP.size() && i < pathQ.size(); i++) {
if (pathP.get(i) == pathQ.get(i)) {
result = pathP.get(i);
} else {
break;
}
}
return result;
}
private boolean getPath(TreeNode root, TreeNode n, List<TreeNode> path) {
if(root==n) {
return true;
}
if(root.left!=null) {
path.add(root.left);
if(getPath(root.left, n, path)) return true;
path.remove(path.size()-1);
}
if(root.right!=null) {
path.add(root.right);
if(getPath(root.right, n, path)) return true;
path.remove(path.size()-1);
}
return false;
}
}
Solution
遍历所有结点,找到p, q,同时记录下路径。遍历两条路径,最后一个相同的结点即为结果。
网友评论