问题
给定一棵二叉树和两个节点,找出这两个节点最近的一个公共父节点。
- 给出的两个节点一定在树中存在;
- 结点的值是随机的,可能会重复,结点中只包含left和right两个子结点,没有指向父节点的parent。
此题可参考LeetCode 236。
思路
考虑两个结点的存在情况:
- 一个节点为是另外一个节点的子或孙子节点,此时只要判断root节点等于其中一个节点即可;
- 两个节点分属两支,此时两个节点都是root节点的子或孙结点,同时在root.left和root.right中各能找到一个节点;
- 如果不属于以上两种情况,对root.left和root.right递归判断。
还有一种比较直接的方法,分别找出从root节点到两个结点的路径并保存到一个链表里,再对路径比较得到最近公共父节点。
代码
1、递归方法
/*class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int val) {this.val = val;}
*}
*/
public TreeNode findAncestor(TreeNode root, TreeNode node1, TreeNode node2) {
if (root == null) return null;
if (root == node1 || root == node2) return root;
TreeNode left = findAncestor(root.left, node1, node2);
TreeNode right = findAncestor(root.right, node1, node2);
if (left != null && right != null) return root;
return right == null ? left : right;
}
2、直接法
public TreeNode findAncestor(TreeNode root, TreeNode node1, TreeNode node2) {
List<TreeNode> path1 = new ArrayList<>();
List<TreeNode> path2 = new ArrayList<>();
path1.add(root);
getPath(root, node1, path1);
path2.add(root);
getPath(root, node2, path2);
TreeNode res = null;
for (int i = 0; i < path1.size() && i < path2.size(); i++) {
if (path1.get(i) == path2.get(i))
res = path1.get(i);
else
break;
}
return res;
}
private boolean getPath(TreeNode root, TreeNode node, List<TreeNode> path) {
if (root == node) return true;
if (root.left != null) {
path.add(root.left);
if (getPath(root.left, node, path)) return true;
else path.remove(path.size()-1);
}
if (root.right != null) {
path.add(root.right);
if (getPath(root.right, node, path)) return true;
else path.remove(path.size()-1);
}
reture false;
}
给定二叉树和两个节点,找到它们最近的公共父节点。如果一个节点是另一个的子或孙子,根节点即为答案;否则,通过递归或记录路径找到最近公共父节点。
8521

被折叠的 条评论
为什么被折叠?



