二叉树的深度和高度
(对某个节点来说)
深度是指从根节点到该节点的最长简单路径边的条数;
高度是指从最下面的叶子节点到该节点的最长简单路径边的条数;
(对二叉树)
深度是从根节点数到它的叶节点;
高度是从叶节点数到它的根节点;
注意: 树的深度和高度一样,但是具体到树的某个节点,其深度和高度不一样。
回溯算法
回溯算法的定义:回溯算法也叫试探法,它是一种系统地搜索问题的解的方法。
算法的基本思想是:从一条路往前走,能进则进,不能进则退回来,换一条路再试。
递归函数的开头写好中止条件,或者跳出条件,满足条件才将当前结果加入总结果中,或者不满足让函数return,防止重复遍历已经经过的地点不在经过(已经搜索过的解空间不再重复搜索。遍历过当前节点后,为了回溯到上一步,要去掉已经加入到结果list中的当前节点。
104.二叉树的最大深度
首先第一种方法是使用递归法来做。可以使用左右中的后续遍历(求高度),或者中左右的前序遍历(求深度)。二叉树的最大深度等于二叉树的高度。
递归法-后序遍历
class Solution {
public:
//递归法,后序遍历
int getDepth(TreeNode* root) {
if(root == NULL) return 0;
int leftdepth = getDepth(root->left); // 左
int rightdepth = getDepth(root->right); // 右
int depth = 1 + max(leftdepth, rightdepth); // 中
return depth;
}
int maxDepth(TreeNode* root)
{
return getDepth(root);
}
};
递归法-前续遍历
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 == NULL) return result;
getdepth(root, 1);
return result;
}
};
559.n叉树的最大深度
class solution {
public:
int maxdepth(node* root) {
if (root == 0) return 0;
int depth = 0;
for (int i = 0; i < root->children.size(); i++) {
depth = max (depth, maxdepth(root->children[i]));
}
return depth + 1;
}
};
111.二叉树的最小深度
class Solution {
public:
int getDepth(TreeNode* node){
int depth;
if(node == nullptr) return 0;
int left = getDepth(node->left);
int right = getDepth(node->right);
if(node->left == nullptr && node->right != nullptr){
return depth = 1 + right;
}
if(node->left != nullptr && node->right == nullptr){
return depth = 1 + left;
}
return depth = 1 + min(left,right);
}
int minDepth(TreeNode* root) {
return getDepth(root);
}
};
222.完全二叉树的节点个数
class Solution {
public:
int countNodes(TreeNode* root) {
if(root == NULL) return 0;
TreeNode* left = root->left;
TreeNode* right = root->right;
int leftdepth = 0,rightdepth = 0;
while(left){
left = left->left;
leftdepth++;
}
while(right){
right = right->right;
rightdepth++;
}
if(leftdepth == rightdepth)
return (2 << leftdepth) - 1; //左位移操作,表示2^leftdepth
return countNodes(root->left) + countNodes(root->right) + 1;//向左向右总会遇见满二叉树
}
};