Maximum Depth of Binary Tree 二叉樹的深度

Given a binary tree,find its maximum depth.node

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.spa

此題是經典的求二叉樹深度深度題目,可採用遞歸的方式,以此求每一個節點的左子樹深度和右子樹深度,而後返回該節點左右子樹深度最大的那個即爲該節點的深度code

具體代碼以下:blog

 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 };
相關文章
相關標籤/搜索