首先明确概念:
二叉树的高度:叶子节点到当前节点的节点数
二叉树的深度:根节点到当前节点的节点数
故求**高度**可用**后序遍历**,而**深度**可用**前序**遍历
class Solution {
public:
// 返回以该节点为根节点的二叉树的高度,如果不是二叉搜索树了则返回-1
int getDepth(TreeNode* node) {
if (node == NULL) {
return 0;
}
int leftDepth = getDepth(node->left); // 左
if (leftDepth == -1) return -1;
int rightDepth = getDepth(node->right); // 右
if (rightDepth == -1) return -1;
int result;
if (abs(leftDepth - rightDepth) > 1) { // 中
result = -1;
} else {
result = 1 + max(leftDepth, rightDepth); // 以当前节点为根节点的最大高度
}
return result;
}
bool isBalanced(TreeNode* root) {
return getDepth(root) == -1 ? false : true;
}
};
法二(自己):
先写一个求root树高度的函数,然后后序遍历(因为要先得到左右子树的高度才能做判断是否为平衡二叉树,故为后序遍历)树的每个结点,看以每个结点为root的树是否为平衡二叉树,若发现有不是的,则直接返回false;
求二叉树最大深度,即求根节点的最大高度,故可以后序遍历
法一:后序遍历
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == NULL)
return 0;
int left = maxDepth(root->left);
int right = maxDepth(root->right);
return max(left, right) + 1;
}
};
法二:前序遍历
根据深度的定义,可以使用前序遍历,中左右,这才是真正求深度的逻辑!
代码如下:(充分表现出求深度回溯的过程)
class solution {
public:
int result;
void getdepth(treenode* node, int depth) {
result = depth > result ? depth : result; // 中
if (node->left == null && node->right == null) return ;
if (node->left) { // 左
depth++; // 深度+1
getdepth(node->left, depth);
depth--; // 回溯,深度-1
}
if (node->right) { // 右
depth++; // 深度+1
getdepth(node->right, depth);
depth--; // 回溯,深度-1
}
return ;
}
int maxdepth(treenode* root) {
result = 0;
if (root == 0) return result;
getdepth(root, 1);
return result;
}
};
简化一下代码如下:
class Solution {
public:
int res = 0;//因为是前序遍历,所以需要用一个变量记录下来,后序遍历是可以先得到左右子树的高度,再求max
void getDepth(TreeNode* root, int depth){
res = res > depth?res:depth;
if(root->left == NULL && root->right == NULL) return;
if(root->left) getDepth(root->left, depth + 1);
if(root->right) getDepth(root->right, depth + 1);
return;
}
int maxDepth(TreeNode* root) {
if(root == NULL) return 0;
getDepth(root, 1);
return res;
}
};
法三:迭代法,最大深度也就是二叉树的层数,则可用层序遍历
class solution {
public:
int maxdepth(treenode* root) {
if (root == null) return 0;
int depth = 0;
queue<treenode*> que;
que.push(root);
while(!que.empty()) {
int size = que.size();
depth++; // 记录深度
for (int i = 0; i < size; i++) {
treenode* node = que.front();
que.pop();
if (node->left) que.push(node->left);
if (node->right) que.push(node->right);
}
}
return depth;
}
};
不能简单的返回1 + min(leftDepth, rightDepth),这是在当前结点有左右孩子的情况。
记住深度的定义,是根节点到叶子结点的节点数,叶子结点是左右孩子都为空。
如下图所示:
如果这么求的话,没有左孩子的分支会算为最短深度。
故在写返回值的时候要注意,如果左孩子为空,右孩子不为空,则最小深度是1 + 右子树的深度,同理,若右子树为空,左子树不为空,最小深度是1 + 左子树深度。
若左右子树都不为空,则放回 1 + min(leftDepth, rightDepth)
class Solution {
public:
int minDepth(TreeNode* root) {
if(root == NULL)
return 0;
int l = minDepth(root->left);
int r = minDepth(root->right);
if(root->left == NULL && root->right != NULL){
return r + 1;
}
if(root->right == NULL && root->left != NULL)
return l +1;
return min(l, r) + 1;
}
};
当然,还可以使用迭代法。 使用层序遍历。