Repository navigation
Expand file tree
/
Copy pathBinaryTree.java
More file actions
77 lines (55 loc) · 1.46 KB
/
Copy pathBinaryTree.java
File metadata and controls
77 lines (55 loc) · 1.46 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
68
69
70
71
72
73
74
75
76
77
package binaryTreeBasics;
import java.util.Scanner;
public class BinaryTree {
Scanner sc;
Node root;
public BinaryTree() {
sc = new Scanner(System.in);
}
// creates a binary tree and returns the root node
Node createBinaryTree() {
System.out.println("Enter node data");
int data = sc.nextInt();
if(data == -1) return null;
Node node = new Node(data);
System.out.println("Enter "+ data + "'s left data");
node.left = createBinaryTree();
System.out.println("Enter "+ data + "'s right data");
node.right = createBinaryTree();
return node;
}
void inOrderTraversal(Node root) {
if(root == null) return;
inOrderTraversal(root.left); // Left
System.out.println(root.data); // Node
inOrderTraversal(root.right); // Right
}
void preOrderTraversal(Node root) {
if(root == null) return;
System.out.println(root.data); // Node
preOrderTraversal(root.left); // Left
preOrderTraversal(root.right); // Right
}
int heightOfABinaryTree(Node root) {
if(root == null) return 0;
int lh = heightOfABinaryTree(root.left);
int rh = heightOfABinaryTree(root.right);
return Math.max(lh, rh) + 1;
}
void printNodesAtKDistance(Node root, int k) {
if(root == null) return;
if(k == 0) {
System.out.println(root.data);
return;
}
printNodesAtKDistance(root.left, k-1);
printNodesAtKDistance(root.right, k-1);
}
}
class Node {
int data;
Node left, right;
public Node(int data) {
this.data = data;
}
}