标签:HERE lca this nts == 说明 between exist unique
class Solution { public static TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (root == null) { return null; } TreeNode left = lowestCommonAncestor(root.left, p, q); TreeNode right = lowestCommonAncestor(root.right, p, q); if (root == p || root == q) { boolean rootright = true; return root; } if (left != null && right != null) { boolean notempty = true; return root; } return right == null ? left : right; } }
法2:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { private class ResultType{ boolean hasP; boolean hasQ; TreeNode lca; public ResultType(boolean hasP, boolean hasQ, TreeNode lca) { this.hasP = hasP; this.hasQ = hasQ; this.lca = lca; } } public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { ResultType rt = helper(root, p, q); return rt.lca; } private ResultType helper(TreeNode root, TreeNode p, TreeNode q) { if (root == null) { return new ResultType(false, false, null); } // if (root == p) { // return new ResultType(true, false, null); // } // if (root == q) { // return new ResultType(false, true, null); // } // P1: 一个是不要处理的这么细,拿root和pq是否相等也这样处理,尽可能包含在下面的递归里。另一个是hasP本来就要考虑当前root是不是的情况,如果左右都没有p但本root就是p那也得是hasP啊。这样才能正确处理到p是q的祖先的情况。 ResultType left = helper(root.left, p, q); ResultType right = helper(root.right, p, q); boolean hasP = left.hasP || right.hasP || root == p; boolean hasQ = left.hasQ || right.hasQ || root == q; TreeNode lca = null; if (hasP && hasQ) { if (left.lca != null) { lca = left.lca; } else if (right.lca != null) { lca = right.lca; } else { lca = root; } } return new ResultType(hasP, hasQ, lca); } }
leetcode236 - Lowest Common Ancestor of a Binary Tree - medium
标签:HERE lca this nts == 说明 between exist unique
原文地址:https://www.cnblogs.com/jasminemzy/p/9698483.html