Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Subscribe to see which companies asked this question
非递归实现:
int maxDepth(TreeNode* root) { int maxDepth = 0; if (root == nullptr) return maxDepth; stack<TreeNode*> sta; sta.push(root); TreeNode* lastRoot = root; while (!sta.empty()) { root = sta.top(); if (lastRoot != root->right) { if (lastRoot != root->left) { if (root->left != nullptr) { sta.push(root->left); continue; } } if (root->right != nullptr) { sta.push(root->right); continue; } maxDepth = sta.size() > maxDepth ? sta.size() : maxDepth; } lastRoot = root; sta.pop(); } return maxDepth; }
递归实现:
int maxDepth(TreeNode* root) { if (root == nullptr) return 0; int leftDepth = maxDepth(root->left) + 1; int rightDepth = maxDepth(root->right) + 1; return leftDepth > rightDepth ? leftDepth : rightDepth; }