-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathAnhLinh.java
74 lines (60 loc) · 1.36 KB
/
AnhLinh.java
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
public class AnhLinh
{
Node root;
// A utility function to check if a given node is leaf or not
static boolean isLeaf(Node node)
{
if (node == null)
return false;
if (node.left == null && node.right == null)
return true;
return false;
}
// This function returns sum of all left leaves in a given
// binary tree
static private int leftLeavesSum(Node node)
{
// Initialize result
int res = 0;
// Update result if root is not NULL
if (node != null)
{
// If left of root is NULL, then add key of
// left child
// 1
// 2 3
//4
if (isLeaf(node.left))
res += node.left.data;
else // Else recur for left child of root
res += leftLeavesSum(node.left);
// Recur for right child of root and update res
res += leftLeavesSum(node.right);
}
// return result
return res;
}
// Driver program
public static void main(String args[])
{
AnhLinh tree = new AnhLinh();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
System.out.println("The sum of leaves is " +
tree.leftLeavesSum(tree.root));
}
}
// Java program to find sum of all left leaves
class Node
{
int data;
Node left, right;
Node(int item)
{
data = item;
left = right = null;
}
}
// This code is contributed by Mayank Jaiswal