题目链接:
题解
思路:该题的解法与
代码(C++):
//递归法 //后序遍历 class Solution1 { public: int maxDepth(Node* root) { if (root == nullptr) return 0; int size = root->children.size(); int result = 0; for (int i = 0; i < size; i++) { int level = maxDepth(root->children[i]); result = result > level ? result : level; } return result + 1; } }; //递归法 //前序遍历 class Solution2 { public: int result; void getDepth(Node* node, int depth) { result = result > depth ? result : depth; if (node->children.empty()) return; int size = node->children.size(); for (int i = 0; i < size; i++) { depth++; //深度+1 getDepth(node->children[i], depth); depth--; //回溯 深度-1 } return; } int maxDepth(Node* root) { result = 0; if (root == nullptr) return result; getDepth(root,1); return result; } }; //迭代法(队列) //层次遍历 class Solution3 { public: int maxDepth(Node* root) { queue<Node*> que; if (root != nullptr) que.push(root); int depth = 1; while (!que.empty()) { int size = que.size(); for (int i = 0; i < size; i++) { Node* node = que.front(); que.pop(); for (int i = 0; i < node->children.size(); i++) { que.push(node->children[i]); } } depth++; } return depth - 1; } };