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. 提交的错误,不知道为什么,但是要自己避免。

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.

提交的错误,不知道为什么,但是要自己避免。

 

C++实现代码:

#include<iostream>
#include<new>
#include<vector>
#include<stack>
using namespace std;

//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)
        {
            if(root->left==NULL&&root->right==NULL)
                return 1;
            int leftDepth=maxDepth(root->left);
            int rightDepth=maxDepth(root->right);
            return leftDepth>= rightDepth ?(leftDepth+1):(rightDepth+1);
        }
        return 0;
    }
    void createTree(TreeNode *&root)
    {
        int i;
        cin>>i;
        if(i!=0)
        {
            root=new TreeNode(i);
            if(root==NULL)
                return;
            createTree(root->left);
            createTree(root->right);
        }
    }
};

int main()
{
    Solution s;
    TreeNode *root;
    s.createTree(root);
    cout<<s.maxDepth(root);
    cout<<endl;
}

 

相关文章
|
5月前
Leetcode Minimum Depth of Binary Tree (面试题推荐)
计算树的最小深度 很简单的一道题,只需要遍历一次树,到叶子节点的时候计算一下深度和当前最小深度比较,保存最小值就行。 我在这用了一个全局变量 mindepth。总感觉我这代码写的不够简练,求更精简的方法。
24 0
LeetCode 104. Maximum Depth of Binary Tree
给定一颗二叉树,返回其最大深度. 注意:深度从1开始计数.
44 0
LeetCode 104. Maximum Depth of Binary Tree
LeetCode 111. Minimum Depth of Binary Tree
给定一棵二叉树,返回其最短深度. 题目要求是返回一颗二叉树从根节点到到所有叶节点中,深度最小的值.
58 0
LeetCode 111. Minimum Depth of Binary Tree
|
Go
LeetCode 124. Binary Tree Maximum Path Sum
给定一个非空二叉树,返回其最大路径和。 本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。
50 0
LeetCode 124. Binary Tree Maximum Path Sum
LeetCode之Maximum Depth of Binary Tree
LeetCode之Maximum Depth of Binary Tree
85 0
|
Java
[LeetCode] Maximum Depth of Binary Tree
链接:https://leetcode.com/submissions/detail/136407355/难度:Easy题目:104. Maximum Depth of Binary Tree Given a binary tree, find its maximum depth.
947 0
|
Java
[LeetCode] Minimum Depth of Binary Tree
链接:https://leetcode.com/problems/minimum-depth-of-binary-tree/description/难度:Easy题目:111.
823 0