`
SunnyYoona
  • 浏览: 364950 次
社区版块
存档分类
最新评论

[LeetCode]104.Maximum Depth of Binary Tree

阅读更多

【题目】

Maximum Depth of Binary Tree

Total Accepted:5260Total Submissions:11532My 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;
}



分享到:
评论

相关推荐

    LeetCode去除数组重复元素-Arithmetic-Swift:一些算法的swift实现

    LeetCode去除数组重复元素 Arithmetic-Swift 一些算法的swift实现 桶排序 冒泡排序 快速排序 ##正好看见LeetCode可以刷Swift的题目 开始慢慢刷 swift有playground 做起来还是相当方便的 已完成题目 ----2016.9.30 两...

    leetcode答案-LeetCode-Trip:LeetCode刷题代码,大佬勿入

    leetcode 答案 LeetCode-Trip LeetCode刷题代码,大佬勿入。 为一年后的研究生找工作准备 目标是BAT的算法岗哈哈哈哈哈 争取做到每日一更 嗯…… 19.10.22:鸽了这么久,我又回来了……主要在实验室天天没啥事,过于...

    LeetCode最全代码

    * [Binary Search Tree](https://github.com/kamyu104/LeetCode#binary-search-tree) * [Breadth-First Search](https://github.com/kamyu104/LeetCode#breadth-first-search) * [Depth-First Search]...

    四平方和定理leetcode-leetcode-practice:个人LeetCode练习代码

    104.maximum-depth-of-binary-tree (二叉树的最大深度) 105.construct-binary-tree-from-preorder-and-inorder-traversal (从前序与中序遍历序列构造二叉树) 106.construct-binary-tree-from-inorder-and-postorder-...

    leetcode答案-leetcode-java:leetcode的Java代码

    leetcode 答案leetcode-java leetcode.com 的 Java 答案 ================索引================ com.leetcode.array Search a 2D Matrix Spiral Matrix com.leetcode.list Linked List Cycle Linked List Cycle II ...

    Leetcode的ac是什么意思-LeetCodeInJava:leetcode-java

    Leetcode的ac是什么意思 LeetCodeInJava List #98 Validate Binary Search Tree #100 Same Tree #104 Maximum Depth of Binary Tree #122 Best Time to Buy and Sell Stock II #136 Single Number #150 Evaluate ...

    leetcode-js:算法和数据结构是一个程序员的灵魂,LeetCode JavaScript TypeScript 题解

    leetcode-js Leecode 经典题目 JavaScript TypeScript 题解。 Leetcode's answers by ...104.二叉树的最大深度 (Maximum Depth of Binary Tree) 118.杨辉三角 (Pascal's Triangle) 119.杨辉三角 II (Pascal's Triangle)

    javalruleetcode-what_the_dead_men_say:what_the_dead_men_say

    java lru leetcode what_the_dead_men_say 所以这只是一个 repo,我从leetcode.com存储我的问题解决方案。 二叉树 0098 Validate Binary ...Tree ...Binary ...Maximum depth of binary tree - Java Iterative

    cpp-算法精粹

    Maximum Depth of Binary Tree Path Sum Path Sum II Binary Tree Maximum Path Sum Populating Next Right Pointers in Each Node Sum Root to Leaf Numbers LCA of Binary Tree 线段树 Range Sum Query - Mutable ...

    lrucacheleetcode-LeetCode_Note:leetcode个人笔记

    [104_maximum-depth-of-binary-tree.cpp] [105_construct-binary-tree-from-preorder-and-inorder-traversal.cpp] [106_construct-binary-tree-from-inorder-and-postorder-traversal.cpp] [107_binary-tree-level-...

    leetcode答案-leetcode:leetcode

    leetcode 答案 leetcode 08/18 Unique Paths 应该是简单的数学排列组合问题,提炼一下其实就一句话:有m个黑球,n个白球,有多少种不同的排列方式。 我数学太差,没找到答案,直接上了动态规划。 Unique Paths II ...

    2sumleetcode-LeetCode:力码

    2sum leetcode 轮廓 1_count_and_say.cpp - super_ugly_number.cpp ...invert_Binary_Tree.cpp - 对称树.cpp - BST_Or_Not.cpp - level_order_traversal.cpp - exponentiation_by_squaring.cpp - Maximum_Depth_B

    leetcode跳跃-Algorithm:算法学习,包括leetcode算法题,

    maximum-depth-of-binary-tree 105 construct-binary-tree-from-preorder-and-inorder-traversal 无官方题解 106 construct-binary-tree-from-inorder-and-postorder-traversal 无官方题解 116 populating-next-...

Global site tag (gtag.js) - Google Analytics