Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitb0b2dba

Browse files
committed
Added Lowest Common Ancestor of a Binary Tree II.java
1 parent433c62a commitb0b2dba

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
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+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp