Maximum Depth of Binary Tree leetcode

Bertha 。 2022-01-09 23:11 445阅读 0赞

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

非递归实现:

  1. int maxDepth(TreeNode* root) {
  2. int maxDepth = 0;
  3. if (root == nullptr)
  4. return maxDepth;
  5. stack<TreeNode*> sta;
  6. sta.push(root);
  7. TreeNode* lastRoot = root;
  8. while (!sta.empty())
  9. {
  10. root = sta.top();
  11. if (lastRoot != root->right)
  12. {
  13. if (lastRoot != root->left) {
  14. if (root->left != nullptr) {
  15. sta.push(root->left);
  16. continue;
  17. }
  18. }
  19. if (root->right != nullptr) {
  20. sta.push(root->right);
  21. continue;
  22. }
  23. maxDepth = sta.size() > maxDepth ? sta.size() : maxDepth;
  24. }
  25. lastRoot = root;
  26. sta.pop();
  27. }
  28. return maxDepth;
  29. }

递归实现:

  1. int maxDepth(TreeNode* root) {
  2. if (root == nullptr)
  3. return 0;
  4. int leftDepth = maxDepth(root->left) + 1;
  5. int rightDepth = maxDepth(root->right) + 1;
  6. return leftDepth > rightDepth ? leftDepth : rightDepth;
  7. }

转载于:https://www.cnblogs.com/sdlwlxf/p/5173431.html

发表评论

表情:
评论列表 (有 0 条评论,445人围观)

还没有评论,来说两句吧...

相关阅读