zoukankan      html  css  js  c++  java
  • Maximum Depth of Binary Tree leetcode

    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;
    }
  • 相关阅读:
    HDU 4472 Count DP题
    HDU 1878 欧拉回路 图论
    CSUST 1503 ZZ买衣服
    HDU 2085 核反应堆
    HDU 1029 Ignatius and the Princess IV
    UVa 11462 Age Sort
    UVa 11384
    UVa 11210
    LA 3401
    解决学一会儿累了的问题
  • 原文地址:https://www.cnblogs.com/sdlwlxf/p/5173431.html
Copyright © 2011-2022 走看看