zoukankan      html  css  js  c++  java
  • 559.N叉树的最大深度(LeetCode)

    dfs深度优先搜索

    (注意:题目有思路时要注意搜索边界条件!!!)

    1.要判断根结点的子节点是否为空,如果没有子节点,那么深度就是1个根结点。

    2.设置一个深度最大值ans,递归搜索得到一个深度值时,若搜索到的深度大于当前ans的值,就更新ans值。

    3.要注意,存储子节点时用的是vector容器,容器中装的是Node类型的指针,当定义一个迭代器指针it时(vector<Node*>::iterator it),it指向Node类指针,即 * it=children(可以说it的内容存放的是Node类指针的地址)程序递归调用的参数是Node类型的指针,所以要解引用,* it=children (children是Node类型的指针)。也可以令Node *p=*it

     1 // Definition for a Node.
     2 class Node {
     3 public:
     4     int val;
     5     vector<Node*> children;
     6 
     7     Node() {}
     8 
     9     Node(int _val) {
    10         val = _val;
    11     }
    12 
    13     Node(int _val, vector<Node*> _children) {
    14         val = _val;
    15         children = _children;
    16     }
    17 };
    18 */
    19 class Solution {
    20 public:
    21     int ans=-1;
    22     void dfs(Node* root,int deep){
    23         //没有子节点,递归结束
    24         if(root->children.empty()){
    25             if(ans<deep){
    26                 ans=deep;
    27             }
    28             return ;
    29         }
    30 
    31         else{
    32             vector<Node*>::iterator it=root->children.begin();
    33             //迭代器指针指向子节点指针  
    34             for(;it!=root->children.end();it++){
    35                 Node *p=*it;  
    36                 dfs(p,deep+1);   //子节点不空,向下递归并且深度加1
    37             }
    38         }
    39     }
    40 
    41     int maxDepth(Node* root) {
    42         if(root==NULL)  return 0;
    43         else{
    44             dfs(root,1);  
    45             return ans;
    46         }     
    47     }
    48 };
    View Code
  • 相关阅读:
    卡特兰数
    hdu 1023 Train Problem II
    hdu 1022 Train Problem
    hdu 1021 Fibonacci Again 找规律
    java大数模板
    gcd
    object dection资源
    Rich feature hierarchies for accurate object detection and semantic segmentation(RCNN)
    softmax sigmoid
    凸优化
  • 原文地址:https://www.cnblogs.com/mld-code-life/p/12291754.html
Copyright © 2011-2022 走看看