-
Notifications
You must be signed in to change notification settings - Fork 0
/
LC-BinaryTreeDepth.cpp
74 lines (60 loc) · 1.4 KB
/
LC-BinaryTreeDepth.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
72
73
74
#include <iostream>
using namespace std;
#include <vector>
#include <cmath>
#include <time.h>
#include <string>
#include <stack>
#include <queue>
#include <algorithm>
#include <list>
#include <set>
#include <unordered_set>
#include <map>
#include <unordered_map>
#include <bits/stdc++.h>
struct TreeNode
{
int val;
struct TreeNode* left;
struct TreeNode* right;
};
struct TreeNode* create()
{
struct TreeNode* new_node= (struct TreeNode*)malloc(sizeof(struct TreeNode));
int x;
printf("Enter data to node: ");
scanf("%d", &x);
if(x==-1)
return NULL;
new_node->val= x;
printf("Enter for Left Child of %d\n", new_node->val);
new_node->left= create();
printf("Enter for Right Child of %d\n", new_node->val);
new_node->right= create();
return new_node;
}
int treeDepth(TreeNode* root){
if(root==NULL) return -1;
int level= 0;
queue<struct TreeNode*> q;
q.push(root);
while(1){
int size= q.size();
if(size==0) return level-1; // depth= level-1
while(size>0){
struct TreeNode* temp= q.front();
q.pop();
if(temp->left!=NULL) q.push(temp->left);
if(temp->right!=NULL) q.push(temp->right);
size--;
}
level++;
}
return level-1;
}
int main(){
struct TreeNode* root= create();
cout<< treeDepth(root);
return 0;
}