LeetCode Maximum Depth of Binary Tree (求树的深度)
2015-07-11 12:03
357 查看
题意:给一棵二叉树,求其深度。
思路:递归比较简洁,先求左子树深度,再求右子树深度,比较其结果,返回:max_one+1。
AC代码
思路:递归比较简洁,先求左子树深度,再求右子树深度,比较其结果,返回:max_one+1。
/** * 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 a=maxDepth(root->left); int b=maxDepth(root->right); return a>b?a+1:b+1; } };
AC代码