[LeetCode] 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.
这道题非常直接,只需要递归深搜就可以。需要注意的是递归的终止条件:root为空,深度为0;root没有孩子,深度为1。如果存在孩子,则递归深搜下去。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int maxDepth(TreeNode *root) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. if(root == NULL) return 0; if(root -> left == NULL && root -> right == NULL) return 1; int leftDepth = 0, rightDepth = 0; if(root -> left != NULL) leftDepth = maxDepth(root -> left) + 1; if(root -> right != NULL) rightDepth = maxDepth(root -> right) + 1; return (leftDepth > rightDepth) ? leftDepth : rightDepth; } };
写完后看了博客园另一位博主的写法,发现自己的第一个if其实只是为了填补后面写的代码的漏洞,这个问题完全可以用精简得多的方式写出来。/ * Definition for binary tree
* struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int maxDepth(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function if (root == NULL) return 0; return max(maxDepth(root->left),maxDepth(root->right)) + 1; } };