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 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 int maxDepth(TreeNode *root) { 13 if(root == NULL) 14 return 0; 15 16 int nleft = maxDepth(root->left); 17 int nright = maxDepth(root->right); 18 19 return (nleft > nright) ? (nleft+1) : (nright+1); 20 } 21 };