【Tree】BFS求树的深度

 1 /**************************
 2 https://leetcode.com/problems/maximum-depth-of-binary-tree/
 3 @date 2015.5.12
 4 @description
 5 给定一个二叉树,判断树的最大深度(也是树的高度)
 6 按照题目的定义:树的最大深度指的是,从根节点到最远叶节点的途径中节点的个数。空树的深度为0
 7 
 8 @solution
 9 两种思路:
10 1.DFS 递归算出左右子树的深度,再取最大;
11 2.BFS 借助辅助队列,将同一层次的节点一起入队,在外的while循环统计层次数
12 
13 ***************************/
14 
15 #include <iostream>
16 #include <queue>
17 
18 using namespace std;
19 
20 struct TreeNode{
21     int val;
22     TreeNode *left;
23     TreeNode *right;
24     TreeNode(int x): val(x), left(NULL), right(NULL){}
25 } ;
26 
27 
28 class Solution{
29 public:
30         int maxDepth(TreeNode *root){
31         if (!root) return 0;
32 
33         int depth = 0; // 记录树深度
34         queue<TreeNode *> temp; // 借助辅助队列
35         temp.push(root);
36         while(!temp.empty()){
37             ++depth; // for循环体现BFS思想 把同一层的节点放在一个for循环里,循环外++depth
38             for (int i = 0, n = temp.size(); i < n; i++){
39                 TreeNode *node = temp.front();
40                 temp.pop();
41                 if (node->left != NULL)
42                     temp.push(node->left);
43                 if (node->right != NULL)
44                     temp.push(node->right);
45             }
46 
47         }
48 
49         return depth;
50     }
51 };
52 
53 TreeNode* insert(TreeNode *root, int data){
54     TreeNode *ptr = root;
55     TreeNode *tempNode;
56     TreeNode *newNode = new TreeNode(data);
57 
58     if (ptr == NULL){
59         return newNode;
60     }else{
61         while (ptr != NULL){
62             tempNode = ptr;
63             if (ptr->val <= data)
64                 ptr = ptr->right;
65             else
66                 ptr = ptr->right;
67         }
68         if (tempNode->val <= data)
69             tempNode->right = newNode;
70         else
71             tempNode->left = newNode;
72     }
73     return root;
74 }
75 
76 int main(){
77     TreeNode *root = NULL;
78     int temp = 0;
79     cin >> temp;
80     while (temp != 0){
81         root = insert(root, temp);
82         cin >> temp;
83     }
84 
85     Solution a;
86     cout << a.maxDepth(root);
87 }

 

posted @ 2015-05-12 10:00  LizSep  阅读(1147)  评论(0编辑  收藏  举报