|
| 1 | +/** |
| 2 | + * Definition for a binary tree node. |
| 3 | + * public class TreeNode { |
| 4 | + * int val; |
| 5 | + * TreeNode left; |
| 6 | + * TreeNode right; |
| 7 | + * TreeNode(int x) { val = x; } |
| 8 | + * } |
| 9 | + */ |
| 10 | +classSolution { |
| 11 | +publicTreeNodelowestCommonAncestor(TreeNoderoot,TreeNodep,TreeNodeq) { |
| 12 | +TreeNoderesult =lca(root,p,q); |
| 13 | +if (result ==p) { |
| 14 | +returncheckIfNodeExist(p,q) ?p :null; |
| 15 | + } |
| 16 | +if (result ==q) { |
| 17 | +returncheckIfNodeExist(q,p) ?q :null; |
| 18 | + } |
| 19 | +returnresult; |
| 20 | + } |
| 21 | + |
| 22 | +privatebooleancheckIfNodeExist(TreeNoderoot,TreeNodetarget) { |
| 23 | +if (root ==target) { |
| 24 | +returntrue; |
| 25 | + } |
| 26 | +if (root ==null) { |
| 27 | +returnfalse; |
| 28 | + } |
| 29 | +returncheckIfNodeExist(root.left,target) ||checkIfNodeExist(root.right,target); |
| 30 | + } |
| 31 | + |
| 32 | +privateTreeNodelca(TreeNoderoot,TreeNodep,TreeNodeq) { |
| 33 | +if (root ==null) { |
| 34 | +returnroot; |
| 35 | + } |
| 36 | +if (root ==p ||root ==q) { |
| 37 | +returnroot; |
| 38 | + } |
| 39 | +TreeNodeleft =lca(root.left,p,q); |
| 40 | +TreeNoderight =lca(root.right,p,q); |
| 41 | +if (left !=null &&right !=null) { |
| 42 | +returnroot; |
| 43 | + } |
| 44 | +returnleft !=null ?left :right; |
| 45 | + } |
| 46 | +} |