zoukankan      html  css  js  c++  java
  • 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 };

  • 相关阅读:
    css -- 元素消失的方法
    设备-地理定位
    css -- 高度相等的列 -- 3列高度相等
    css -- 映像 ,分页(上一页下一页)
    css -- 导航条
    现代JavaScript
    移动网页 -- 结构与属性
    移动网页 -- CSS布局
    JS常规的验证代码
    分享
  • 原文地址:https://www.cnblogs.com/NiBosS/p/11954328.html
Copyright © 2011-2022 走看看