LeetCode | Maximum Depth of Binary Tree(二叉树的深度)

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.

题目解析:

求树的深度,很简单就能想到递归。但也有队列方法,和栈的方法,一一介绍。

方案一:

递归实现:

class Solution {
public:
    int maxDepth(TreeNode* root){
        if(root == NULL)
            return 0;

        int left = maxDepth(root->left);
        int right = maxDepth(root->right);
        int max = left > right? left : right;
        return max+1;
    }
};

方案二:

队列实现,跟前面两道题的意思一样。

class Solution {
public:
    //二叉树最大深度(层次遍历,遍历一层高度加1)
    int maxDepth(TreeNode *root) {
        int height = 0,rowCount = 1;
        if(root == NULL){
            return 0;
        }
        //创建队列
        queue<TreeNode *> queue;
        //添加根节点
        queue.push(root);
        //层次遍历
        while(!queue.empty()){
            //队列头元素
            TreeNode *node = queue.front();
            //出队列
            queue.pop();
            //一层的元素个数减1,一层遍历完高度加1
            rowCount --;
            if(node->left){
                queue.push(node->left);
            }
            if(node->right){
                queue.push(node->right);
            }
            //一层遍历完
            if(rowCount == 0){
                //高度加1
                height++;
                //下一层元素个数
                rowCount = queue.size();
            }
        }
        return height;
    }
 
};


方案三:

栈的实现,过程比较复杂,要仔细跟着流程走。

class Solution {
public:
    int maxDepth(TreeNode *root) {  
        // Start typing your C/C++ solution below  
        // DO NOT write int main() function  
        if(root == NULL) return 0;  
           
        stack<TreeNode*> S;  
           
        int maxDepth = 0;  
        TreeNode *prev = NULL;  
           
        S.push(root);  
        while (!S.empty()) {  
            TreeNode *curr = S.top();  
               
            if (prev == NULL || prev->left == curr || prev->right == curr) {  
                if (curr->left)  
                    S.push(curr->left);  
                else if (curr->right)  
                    S.push(curr->right);  
            } else if (curr->left == prev) {  
                if (curr->right)  
                    S.push(curr->right);  
            } else {  
                S.pop();  
            }  
            prev = curr;  
            if (S.size() > maxDepth)  
                maxDepth = S.size();  
        }  
        return maxDepth;  
    }  
};













点赞