高度与深度
- 高度和深度是相反的表示,深度是从上到下数的,而高度是从下往上数。
- 某节点的深度是指从根节点到该节点的最长简单路径边的条数,而高度是指从该节点到叶子节点的最长简单路径边的条数。
- 这里边的条数是规定根节点的深度和叶子节点的高度是0;力扣中认为根节点的深度和叶子节点的高度为1,故下面求解同力扣.
- 所以树的深度和高度是相等的,而对其他节点来说深度和高度不一定相等。
- 使用前序(中左右),也可以使用后序遍历(左右中),使用前序求的就是深度,使用后序求的是高度
【递归】
int maxDepth(TreeNode* node){
if(node == NULL){
return 0;
}
int leftDepth = maxDepth(node->left);
int rightDepth = maxDepth(node->right);
return 1 + max(leftDepth,rightDepth);
/*
return 1 + max(maxDepth(node->left),maxDepth(node->right));
*/
}
【利用层序遍历】
int maxDepth2(TreeNode* node){
if(node == NULL)
return depth;
int depth = 1;
queue<TreeNode*> que;
que.push(node);
TreeNode* last = node,*nlast = NULL,*cur = node;
while(!que.empty()){
TreeNode* cur = que.front();
//cout << cur->value << " ";
que.pop();
if(cur->left != NULL){
que.push(cur->left);
nlast = cur->left;
}
if(cur->right != NULL){
que.push(cur->right);
nlast = cur->right;
}
if(cur == last &&!que.empty()){
//cout <<"\nlevel " << ++depth << endl;
depth++;
last = nlast;
}
}
return depth;
}