N叉数的最大深度
层次遍历
/* // Definition for a Node. class Node { public: int val; vector<Node*> children; Node() {} Node(int _val) { val = _val; } Node(int _val, vector<Node*> _children) { val = _val; children = _children; } }; */ class Solution { public: int maxDepth(Node* root) { int depth=0; if( root == NULL ) return 0; queue<Node*> my_queue; my_queue.push(root); while(my_queue.empty() != 1) { int size = my_queue.size(); depth +=1; for(int i=0 ; i<size ;i++) { Node* cur = my_queue.front(); my_queue.pop(); for(int j=0 ; j<cur->children.size();j++) { if(cur->children[j] != NULL) my_queue.push(cur->children[j]); } } } return depth; } };
迭代遍历
/* // Definition for a Node. class Node { public: int val; vector<Node*> children; Node() {} Node(int _val) { val = _val; } Node(int _val, vector<Node*> _children) { val = _val; children = _children; } }; */ class Solution { public: int getdepth(Node* cur) { if(cur == NULL) return 0; int depth_nums = 0; for(int i=0 ; i < cur->children.size() ; i++) { depth_nums = max(depth_nums,getdepth(cur->children[i])) ; } return 1 + depth_nums; } int maxDepth(Node* root) { if(root == NULL) return 0; return getdepth(root); } };