LeetCode——二叉樹的最大深度
阿新 • • 發佈:2018-12-30
迭代法:
int maxDepth(TreeNode* root) { int maxleft = 0, maxright = 0, maxnum; if (root == NULL) return 0; maxleft = maxDepth(root->left) + 1; maxright = maxDepth(root->right) + 1; maxnum = max(maxleft, maxright); return maxnum; }
層次遍歷:
int maxDepth(TreeNode* root) { if (root == NULL) return 0; stack<pair<TreeNode*, int>> sta; sta.push(pair<TreeNode*, int>(root, 1)); int maxdep = 1; while(!sta.empty()) { TreeNode* node = sta.top().first; int dep = sta.top().second; sta.pop(); if(node != NULL) { maxdep = max(maxdep, dep); sta.push(pair<TreeNode*, int>(node->left, dep + 1)); sta.push(pair<TreeNode*, int>(node->right, dep + 1)); } } return maxdep; }
標準庫stack:
stack.top()
stack.pop()
stack.push()