-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCheckChildrenSumPropertyOfBinaryTree.java
More file actions
112 lines (84 loc) · 2.98 KB
/
Copy pathCheckChildrenSumPropertyOfBinaryTree.java
File metadata and controls
112 lines (84 loc) · 2.98 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/*
* Author : Hasnain Memon
* Date : 14/12/2024
*/
import java.util.Scanner;
public class CheckChildrenSumPropertyOfBinaryTree {
private Node root;
static class Node {
int data;
Node left, right;
public Node(int data) {
this.data = data;
left = right = null;
}
}
public void printPreOrder(Node node) {
if (node == null) {
return;
}
// first print data of node
System.out.print(node.data + " ");
// then recur on left subtree
printPreOrder(node.left);
// then recur on right subtree
printPreOrder(node.right);
}
public void printInOrder(Node node) {
if (node == null) {
return;
}
// first recur on left subtree
printInOrder(node.left);
// then print data of node
System.out.print(node.data + " ");
// then recur on right subtree
printInOrder(node.right);
}
public void printPostOrder(Node node) {
if (node == null) {
return;
}
// first recur on left subtree
printPostOrder(node.left);
// then recur on right subtree
printPostOrder(node.right);
// then print data of node
System.out.print(node.data + " ");
}
// Task 3: Check the children sum property in binary tree, i.e. for every node data values must be
//equal to the sum of data values of left and right child
public boolean checkChildrenSumProperty(Node root) {
if ((root == null) || (root.left == null && root.right == null)) {
return true;
}
int leftValue = (root.left != null)? root.left.data : 0;
int rightValue = (root.right != null)? root.right.data : 0;
if (root.data != leftValue + rightValue) {
return false;
}
return checkChildrenSumProperty(root.left) && checkChildrenSumProperty(root.right);
}
public static void main(String[] args) {
CheckChildrenSumPropertyOfBinaryTree bt = new CheckChildrenSumPropertyOfBinaryTree();
bt.root = new Node(20);
bt.root.left = new Node(10);
bt.root.right = new Node(10);
bt.root.left.left = new Node(5);
bt.root.left.right = new Node(5);
bt.root.right.left = new Node(5);
bt.root.right.right = new Node(5);
System.out.print("Pre-Order Traversal: ");
bt.printPreOrder(bt.root);
System.out.println();
System.out.print("In-Order Traversal: ");
bt.printInOrder(bt.root);
System.out.println();
System.out.print("Post-Order Traversal: ");
bt.printPostOrder(bt.root);
System.out.println();
// Task 3
System.out.println("Has tree Children Sum Property? " +
((bt.checkChildrenSumProperty(bt.root)? "Yes" : "No")));
}
}