【LeetCode-236】Lowest Common Ancestor of a Binary Tree

来源:互联网 发布:淘宝直通车广告位几个 编辑:程序博客网 时间:2024/05/18 03:51

这道题想用寻找路径的方法来解决,但是最后没能成功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;}}


0 0
原创粉丝点击