题目:
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.
代码:
/**
* Definition for a binary tree node.
* */
typedef struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
}*BinaryTree;
class Solution {
public:
void CreateTree(BinaryTree &T)
{
char data;
cin >> data;
if (data == '#')
T = NULL;
else
{
T = new TreeNode(data - '0');
CreateTree(T->left);
CreateTree(T->right);
}
}
int maxDepth(TreeNode* root) {
if (root ==NULL )
{
return 0;
}
int depthL = maxDepth(root->left);
int depthR = maxDepth(root->right);
return depthL > depthR ? depthL + 1 : depthR + 1;
}
};