-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary_tree.cpp
71 lines (56 loc) · 1.27 KB
/
binary_tree.cpp
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
#include<bits/stdc++.h>
using namespace std;
// 10
// / \
// 20 30
// / \
// 40 50
struct Node{
Node *right;
Node *left;
int data;
Node(int key){
data = key;
right = left = NULL;
}
};
// 4) Height of Binary Tree OR Maximum Depth in a binary tree
int height(Node *root){
if(root == NULL)
return 0;
int lh = height(root->left);
int rh = height(root->right);
return 1+max(lh,rh);
}
// 5) Print Nodes at K distance
void printKthNode(Node *root,int k){
if(root == NULL)
return ;
if(k == 0){
cout<<root->data<<" ";
return;
}
printKthNode(root->left,k-1);
printKthNode(root->right,k-1);
}
// Search node in a binary tree
bool search(Node* root, int x) {
if(root==NULL)
return false;
if(root->data == x)
return true;
return search(root->left,x) || search(root->right,x);
}
int main() {
struct Node *root = new Node(10);
root->left = new Node(20);
root->right = new Node(30);
root->right->left = new Node(40);
root->right->right = new Node(50);
cout<<"Height of Binary Tree:"<<endl;
cout<<height(root)<<" ";
cout<<endl;
// printKthNode(root,0);
// cout<<endl;
return 0;
}