LeetCode-104
Links:https://leetcode.com/problems/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.
思路:递归处理即可.
如果本节点非空,返回左右子节点中深度较大的+1
如果本节点为空,返回0(同时也是递归的终点)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
/** * 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 == NULL) { return 0; } else { int left ,right; left = maxDepth(root->left); right = maxDepth(root->right); if(left>right) { return left+1; } else { return right+1; } } } }; |
【LeetCode】104.Maximum Depth of Binary Tree