这道题想用寻找路径的方法来解决,但是最后没能成功ac,看了一下别人的想法,自己又走弯路了!递归完全可以额!
public class ImportantLowestCommonAncestorofaBinaryTree {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null)
return null;
if (root == p || root == q)
return root;
TreeNode L = lowestCommonAncestor(root.left, p, q);
TreeNode R = lowestCommonAncestor(root.right, p, q);
if (L != null && R != null)
return root;
return L != null ? L : R;
}
}
本文探讨使用递归方法解决二叉树寻找路径的问题,并通过实例展示了如何实现寻找最近公共祖先节点的功能。代码示例清晰易懂,适合初学者理解和实践。
441

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



