104. 二叉树的最大深度(深搜/广搜)

宽度优先搜索,层序遍历各节点,并记录各节点所在层,时间复杂度 O(n)。

 1 /**
 2   * Definition for a binary tree node.
 3   * struct TreeNode {
 4   *     int val;
 5   *     TreeNode *left;
 6   *     TreeNode *right;
 7   *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8   * };
 9   */
10 class Solution {
11 public:
12     struct node {
13         int step; //记录节点所在层
14         TreeNode* root; //节点指针
15         node(int x, TreeNode* p) :step(x), root(p) {}; //节点初始化
16     };
17     queue<node> list;
18     int maxDepth(TreeNode* root) {
19         if (!root) return 0; //过滤特殊数据
20         node v(1, NULL); //设置队列节点存储变量
21         list.push(node(1, root)); //压入头节点
22         while (!list.empty()) {
23             v = list.front();
24             list.pop();
25             if (v.root->left) list.push(node(v.step + 1, v.root->left)); //非空入队
26             if (v.root->right) list.push(node(v.step + 1, v.root->right));
27         }
28         return v.step; //最后一个节点所在层的数值就是数的深度
29     }
30 };

猜你喜欢

转载自www.cnblogs.com/NiBosS/p/11954328.html