[LeetCode] 104. Maximum Depth of Binary Tree

来源:互联网 发布:佳能wifi软件app 编辑:程序博客网 时间:2024/06/10 04:41

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.

题目就是说给你一棵二叉树, 求出这棵树的最大深度是多少

对于二叉树, 使用递归去做就就会使题目变得非常简单了, 对一颗二叉树而言, 它的最大深度就是左右子树中, 深度较大的子树加一

/** * 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) {        if(!root)            return 0;        int left = maxDepth(root->left) + 1;        int right = maxDepth(root->right) + 1;        return left > right ? left : right;    }};
0 0
原创粉丝点击