104. Maximum Depth of Binary Tree
思路:这道题很简单,利用递归定义,一棵树的高度等于左右子树高度较大的加1,对于空树或者只有一个节点的数,高度为1。
1 /** 2 3 * Definition for a binary tree node. 4 * struct TreeNode { 5 * int val; 6 * TreeNode *left; 7 * TreeNode *right; 8 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 9 * }; 10 */ 11 class Solution { 12 public: 13 int maxDepth(TreeNode* root) { 14 if(!root) 15 return 0; 16 else 17 return 1+max(maxDepth(root->left),maxDepth(root->right)); 18 19 } 20 };
