-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathBT_Problem_33.java
More file actions
67 lines (54 loc) · 1.77 KB
/
Copy pathBT_Problem_33.java
File metadata and controls
67 lines (54 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package trees.binaryTree;
public class BT_Problem_33 {
static class Node {
int data;
Node left, right;
}
// temporary node to keep track of Node returned
// from previous recursive call during backtrack
static Node temp = null;
static int k;
// recursive function to calculate Kth ancestor
static Node kthAncestorDFS(Node root, int node ) {
// Base case
if (root == null)
return null;
if (root.data == node|| (temp = kthAncestorDFS(root.left,node)) != null || (temp = kthAncestorDFS(root.right,node)) != null) {
if (k > 0)
k--;
else if (k == 0) {
// print the kth ancestor
System.out.print("Kth ancestor is: "+root.data);
// return null to stop further backtracking
return null;
}
// return current node to previous call
return root;
}
return null;
}
// Utility function to create a new tree node
static Node newNode(int data) {
Node temp = new Node();
temp.data = data;
temp.left = temp.right = null;
return temp;
}
// Driver code
public static void main(String[] args) {
// Let us create binary tree shown in above diagram
Node root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(4);
root.left.right = newNode(5);
k = 2;
int node = 5;
// print kth ancestor of given node
Node parent = kthAncestorDFS(root,node);
// check if parent is not null,
// it means there is no Kth ancestor of the node
if (parent != null)
System.out.println("-1");
}
}