[LeetCode]104.Maximum Depth of Binary Tree

简介:

【题目】

Maximum Depth of Binary Tree

  Total Accepted: 5260  Total Submissions: 11532 My Submissions

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.

【代码】

【递归】

时间复杂度为O(n) 空间复杂度为O(logn)

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int maxDepth(TreeNode *root) {
        if(root == NULL){
            return 0;
        }
        int left = maxDepth(root->left);
        int right = maxDepth(root->right);
        return 1 + max(left,right);
    }
};

【队列】

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
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;
    }

};

【栈】

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
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;  
    }  
};






【测试】

/*********************************
*   日期:2013-12-08
*   作者:SJF0115
*   题目: 104.Maximum Depth of Binary Tree
*   来源:http://oj.leetcode.com/problems/maximum-depth-of-binary-tree/
*   结果:AC
*   来源:LeetCode
*   总结:
**********************************/
#include <iostream>
#include <malloc.h>
#include <stdio.h>
using namespace std;

typedef struct TreeNode{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
}TreeNode,*BiTree;

//按先序序列创建二叉树
int CreateBiTree(BiTree &T){
	int data;
	//按先序次序输入二叉树中结点的值,‘-1’表示空树
	scanf("%d",&data);
	if(data == -1){
		T = NULL;
	}
	else{
		T = (BiTree)malloc(sizeof(TreeNode));
		//生成根结点
		T->val = data;
		//构造左子树
		CreateBiTree(T->left);
		//构造右子树
		CreateBiTree(T->right);
	}
	return 0;
}
//二叉树最大深度(递归)
int maxDepth(TreeNode *root) {
    if(root == NULL){
        return 0;
    }
    int left = maxDepth(root->left);
    int right = maxDepth(root->right);
    return 1 + max(left,right);
}

int main() {
    int i,n;
    BiTree T = NULL;
    CreateBiTree(T);
    printf("%d\n",maxDepth(T));
    return 0;
}



目录
相关文章
|
5月前
Leetcode 53.Maximum Subarray
题意简单,给出一个数组,求出其中最大的子数组和。 这种简单题目背后蕴藏着很巧妙的解题方法。其实只需要遍历一次数组就可以求得解。 思路是这样的,你想想看,如果一段子数组的和是负数, 那么这一段子数组不可能是最大和数组的一部分,丢掉重新从下一个位置开始选。
26 0
|
5月前
Leetcode Minimum Depth of Binary Tree (面试题推荐)
计算树的最小深度 很简单的一道题,只需要遍历一次树,到叶子节点的时候计算一下深度和当前最小深度比较,保存最小值就行。 我在这用了一个全局变量 mindepth。总感觉我这代码写的不够简练,求更精简的方法。
24 0
|
5月前
Leetcode 236. Lowest Common Ancestor of a Binary Tree
根据LCA的定义,二叉树中最小公共祖先就是两个节点p和q最近的共同祖先节点,LCA的定义没什么好解释的,主要是这道题的解法。
16 0
LeetCode contest 190 5418. 二叉树中的伪回文路径 Pseudo-Palindromic Paths in a Binary Tree
LeetCode contest 190 5418. 二叉树中的伪回文路径 Pseudo-Palindromic Paths in a Binary Tree
|
算法 Python
LeetCode 108. 将有序数组转换为二叉搜索树 Convert Sorted Array to Binary Search Tree
LeetCode 108. 将有序数组转换为二叉搜索树 Convert Sorted Array to Binary Search Tree
LeetCode 102. 二叉树的层序遍历 Binary Tree Level Order Traversal
LeetCode 102. 二叉树的层序遍历 Binary Tree Level Order Traversal
LeetCode 104. 二叉树的最大深度 Maximum Depth of Binary Tree
LeetCode 104. 二叉树的最大深度 Maximum Depth of Binary Tree
LeetCode Contest 178-1367. 二叉树中的列表 Linked List in Binary Tree
LeetCode Contest 178-1367. 二叉树中的列表 Linked List in Binary Tree
|
算法
LeetCode 414. Third Maximum Number
给定一个非空数组,返回此数组中第三大的数。如果不存在,则返回数组中最大的数。要求算法时间复杂度必须是O(n)。
66 0
LeetCode 414. Third Maximum Number
|
Python
LeetCode 401. Binary Watch
二进制手表顶部有 4 个 LED 代表小时(0-11),底部的 6 个 LED 代表分钟(0-59)。 每个 LED 代表一个 0 或 1,最低位在右侧。
77 0
LeetCode 401. Binary Watch

热门文章

最新文章