LeetCode刷题(C++)——Maximum Depth of Binary Tree(Easy)

来源:互联网 发布:js promise实现原理 编辑:程序博客网 时间:2024/05/22 07:58

题目描述

Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    int getDepth(TreeNode* p)    {        if(p==NULL)        {            return 0;        }        int LD,RD;        LD = getDepth(p->left);        RD  =getDepth(p->right);        return (LD>RD?LD:RD)+1;    }    int maxDepth(TreeNode* root) {        return getDepth(root);    }};


一种更简便的实现方法

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



1 0