Leetcode104二叉树的最大深度

二叉树的最大深度(C++)

一、问题描述

1.1 问题具体描述

给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。

1.2 二叉树结构

C++的定义如下:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

1.3 预期结果示例

示例:
给定二叉树 [3,9,20,null,null,15,7],
Leetcode104二叉树的最大深度_第1张图片
期望输出结果:3

二、解决思路及代码

2.1 递归

深度优先搜索方法,递归遍历整个二叉树
C++实现:

	int maxDepth(TreeNode* root) {
        if(!root) return 0;
        int leftHeight = maxDepth(root->left);
        int rightHeight = maxDepth(root->right);
        return max(leftHeight, rightHeight)+1;
    }

2.2 迭代

利用栈存储节点,采用DFS的思路,父节点出栈,如果左右子节点存在,进栈,左节点出栈,一直迭代,直到栈为空。
C++实现:

int maxDepth(TreeNode* root) {
        //迭代实现DFS
        if(root==NULL) 
            return 0;
        stack<pair<TreeNode*,int>> S;
        TreeNode* p = root;
        int Depth = 0;
        int MaxDepth = 0;
        S.push(pair<TreeNode*, int>(p, Depth+1));
        while(!S.empty()){
            p = S.top().first;
            Depth = S.top().second;
            S.pop();
            MaxDepth = max(MaxDepth, Depth);
            if(p->right) {
                S.push(pair<TreeNode*, int>(p->right, Depth+1));  
            }
            if(p->left) {
                S.push(pair<TreeNode*, int>(p->left, Depth+1));  
            }
            
        }
        return MaxDepth;
    }

2.3 BFS方法

采用BFS思路,借助队列实现,按层遍历。
C++实现:

class Solution {
public:
    int maxDepth(TreeNode* root) {
        //BFS实现
        if(root==NULL) 
            return 0;
        queue<TreeNode*> Q;
        int Depth = 0;
        Q.push(root);
        while(!Q.empty()){
            int widthsize = Q.size();//每层的节点个数,遍历整个层
            for(int i=0;i<widthsize;i++){
                TreeNode* p = Q.front();
                Q.pop();
                if(p->left) Q.push(p->left);
                if(p->right) Q.push(p->right);
            }
            Depth++;
        }
        return Depth;
    }
};

三、提交结果

3.1 递归法结果

Leetcode104二叉树的最大深度_第2张图片

3.2 迭代法结果

Leetcode104二叉树的最大深度_第3张图片
3.3 BFS结果
Leetcode104二叉树的最大深度_第4张图片

四、结果分析

通过在Leetcode上的提交结果,不难发现三种方法中迭代法的耗时较低,但是三种方法的内存消耗都较大。

你可能感兴趣的:(Leetcode,leetcode,c++,二叉树,队列,数据结构)