- 利用队列,每遍历完一层结点,二叉树的高度就增加1。
- 利用层次遍历
int getDepth(TreeNode *root){
if (root == NULL)
return 0;
queue<TreeNode*> qu;
TreeNode *cur = root;
qu.push(cur);
int depth = 0;
while (!qu.empty()){
int n = qu.size();
for (int i = 0; i < n; i++){
cur = qu.front();
qu.pop();
if (cur->left != NULL){
qu.push(cur->left);
}
if (cur->right != NULL){
qu.push(cur->right);
}
}
depth++;
}
return depth;
}
- 利用子问题求解
int getDepth2(TreeNode *root){
if (root == NULL)
return 0;
return getDepth(root->left) > getDepth(root->right) ?
getDepth(root->left) + 1 : getDepth(root->right) + 1;
}