### 二叉树基本概念
- **Binary Tree(二叉树)**:每个节点最多有两个子节点的树结构。
- **Node(节点)**:二叉树中的基本元素,包含数据和指向子节点的指针。
- **Root(根节点)**:二叉树最顶层的节点,没有父节点。
- **Parent Node(父节点)**:一个节点的直接上层节点。
- **Child Node(子节点)**:一个节点的直接下层节点,分为左子节点(Left Child Node)和右子节点(Right Child Node)。
- **Leaf Node(叶子节点)**:没有子节点的节点。
- **Internal Node(内部节点)**:至少有一个子节点的非根节点。
- **Subtree(子树)**:由一个节点及其所有后代节点组成的树。
- **Depth(深度)**:从根节点到某个节点的路径长度。
- **Height(高度)**:从某个节点到其最远叶子节点的最长路径长度。
### 遍历相关词汇
- **Traversal(遍历)**:按照一定顺序访问二叉树中的所有节点。
- **In - order Traversal(中序遍历)**:左子树 -> 根节点 -> 右子树。
- **Pre - order Traversal(前序遍历)**:根节点 -> 左子树 -> 右子树。
- **Post - order Traversal(后序遍历)**:左子树 -> 右子树 -> 根节点。
- **Level - order Traversal(层序遍历)**:按树的层次从根节点开始,逐层从左到右访问节点。
- **Recursion(递归)**:一种编程技巧,常用于二叉树遍历,函数调用自身来处理子问题。
- **Stack(栈)**:一种后进先出(LIFO)的数据结构,可用于非递归遍历二叉树。
- **Queue(队列)**:一种先进先出(FIFO)的数据结构,常用于层序遍历。
### 特殊二叉树类型
- **Binary Search Tree(二叉搜索树)**:对于树中的每个节点,其左子树中的所有节点值都小于该节点值,右子树中的所有节点值都大于该节点值。
- **Balanced Binary Tree(平衡二叉树)**:每个节点的左右子树的高度差不超过 1 的二叉树。
A binary tree with a height difference of no more than 1 between the left and right subtrees of each node.
- **Complete Binary Tree(完全二叉树)**:除了最后一层外,每一层都被完全填充,并且最后一层的节点都尽可能靠左排列。
Except for the last layer, each layer is completely filled, and the nodes of the last layer are arranged as close to the left as possible.
- **Full Binary Tree(满二叉树)**:每个节点要么有两个子节点,要么没有子节点的二叉树。
Each node in a binary tree either has two child nodes or no child nodes.
### 解题操作与算法相关
- **Insertion(插入)**:在二叉树中添加新节点的操作。
- **Deletion(删除)**:从二叉树中移除节点的操作。
- **Search(搜索)**:在二叉树中查找特定值的节点。
- **Path(路径)**:从一个节点到另一个节点经过的节点序列。
- **Diameter(直径)**:二叉树中任意两个节点之间的最长路径上的边数。
- **Maximum Depth(最大深度)**:从根节点到最远叶子节点的最长路径长度。
- **Minimum Depth(最小深度)**:从根节点到最近叶子节点的最短路径长度。
- **Symmetric(对称)**:二叉树的左右子树互为镜像。
- **Merge(合并)**:将两个或多个二叉树合并为一个。
- **Rebalance(重新平衡)**:对于不平衡的二叉树,通过旋转等操作使其重新达到平衡。
### 代码实现相关
- **Function(函数)**:实现特定功能的代码块。
- **Parameter(参数)**:传递给函数的值。
- **Return Value(返回值)**:函数执行后返回的结果。
- **Variable(变量)**:用于存储数据的标识符。
- **Pointer(指针)**:存储内存地址的变量,在二叉树中用于连接节点。
- **Loop(循环)**:重复执行一段代码的结构,如 `while` 循环、`for` 循环。
- **Condition(条件)**:用于控制程序流程的判断语句,如 `if - else` 语句。
easy
94 中序遍历
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void inorder(TreeNode* root, vector<int>& res) {
if (!root) return;
inorder(root->left, res);
res.push_back(root->val);
inorder(root->right, res);
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
inorder(root, res);
return res;
}
};
104 二叉树的最大深度
左右树的最大深度 + 1
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == nullptr) return 0;
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};
mid
236 二叉树的最近公共祖先
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
// 定义一个名为Solution的类,用于解决二叉树相关问题
class Solution {
public:
// 定义lowestCommonAncestor函数,用于寻找两个节点的最低公共祖先
// 参数root表示二叉树的根节点
// 参数p和q是需要寻找公共祖先的两个节点
// 返回值是最低公共祖先的指针
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
// 如果根节点为空,或者根节点就是p或q之一,那么当前节点就是公共祖先
if (root == NULL || root == p || root == q) return root;
// 递归调用lowestCommonAncestor函数,分别在左子树和右子树中寻找p和q的最低公共祖先
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
// 如果在左右子树中都没有找到p或q,说明当前节点不是公共祖先,返回NULL
if (left == NULL && right == NULL) return NULL;
// 如果左子树中没有找到公共祖先,但右子树中有,说明右子树的返回值就是公共祖先
if (left == NULL) return right;
// 如果右子树中没有找到公共祖先,但左子树中有,说明左子树的返回值就是公共祖先
if (right == NULL) return left;
// 如果左右子树都找到了公共祖先,说明当前节点是p和q的最低公共祖先
return root;
}
};
111 最小深度
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode* root) {
if (root == nullptr) return 0;
queue<TreeNode*> q;
q.push(root);
int depth = 1;
while (!q.empty()) {
int sz = q.size();
for (int i = 0; i < sz; ++i) {
auto cur = q.front();
q.pop();
if (cur->left == nullptr && cur->right == nullptr) return depth;
if (cur->left != nullptr) q.push(cur->left);
if (cur->right != nullptr) q.push(cur->right);
}
depth++;
}
return depth;
}
};
226 翻转二叉树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
dfs(root);
return root;
}
void dfs(TreeNode* root) {
if (!root) return;
TreeNode* tmp = root->left;
root->left = root->right;
root->right = tmp;
dfs(root->left);
dfs(root->right);
}
};
101 对称二叉树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool check(TreeNode* p1, TreeNode* p2) {
if (!p1 && !p2) {
return true;
}
if (!p1 || !p2) {
return false;
}
return (p1->val == p2->val) && (check(p1->left, p2->right)) && (check(p1->right, p2->left));
}
bool isSymmetric(TreeNode* root) {
return check(root, root);
}
};
222 完全二叉树节点数量(从左到右,从上到下依次排满)
复杂度 O(N)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int count = 0; // 统计节点数
void inorder(TreeNode* root) {
if(!root) return;
inorder(root->left);
count += 1;
inorder(root->right);
}
int countNodes(TreeNode* root) {
inorder(root);
return count;
}
};
k
2k 2k+1
h层,则最底层最右边元素是2^{h-1}最左边是2^{h}-1
二分
257 二叉树的所有路径
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
// 创建一个存储路径的结果集
vector<string> result;
// 开始深度优先搜索
dfs(root, "", result);
return result;
}
void dfs(TreeNode* node, string path, vector<string>& result) {
// 如果节点为空,返回
if (node == nullptr) {
return;
}
// *将当前节点值添加到路径中
path += to_string(node->val);
// 如果是叶子节点,将路径添加到结果集中
if (node->left == nullptr && node->right == nullptr) {
result.push_back(path);
return;
}
// 如果不是叶子节点,继续深度优先搜索
path += "->";
dfs(node->left, path, result);
dfs(node->right, path, result);
}
};
404 左叶子之和
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int ans = 0;
int sumOfLeftLeaves(TreeNode* root) {
dfs(root);
return ans;
}
void dfs(TreeNode* r) {
if (r == nullptr) return;
// 是左节点且是叶子节点
if (r->left != nullptr && r->left->left == nullptr && r->left->right == nullptr) {
ans += r->left->val;
}
dfs(r->left);
dfs(r->right);
}
};
100 相同的树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
return dfs(p, q);
}
bool dfs(TreeNode* r1, TreeNode* r2) {
if (r1 == nullptr || r2 == nullptr) return r1 == r2;
if (r1->val != r2->val) return false;
return dfs(r1->left, r2->left) && dfs(r1->right, r2->right);
}
};
513 树最左下角的值
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
// 更新每一层的第一个节点即可
queue<TreeNode*> q;
q.push(root);
int res = root->val;
while (!q.empty()) {
int cs = q.size();
for (int i = 0; i < cs; ++i) {
auto node = q.front();
q.pop();
if (i == 0) res = node->val;
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
}
return res;
}
};
543 二叉树的直径
class Solution {
int ans;
int depth(TreeNode* rt){
if (rt == NULL) {
return 0; // 访问到空节点了,返回0
}
int L = depth(rt->left); // 左儿子为根的子树的深度(即节点数)
int R = depth(rt->right); // 右儿子为根的子树的深度
ans = max(ans, L + R + 1); // 计算d_node即L+R+1 并更新ans
return max(L, R) + 1; // 返回该节点为根的子树的深度
}
public:
int diameterOfBinaryTree(TreeNode* root) {
ans = 1;
depth(root);
return ans - 1;
}
};
102 二叉树的层序遍历
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
if (!root) {
return res;
}
queue<TreeNode*> q;
q.push(root);
while(!q.empty()) {
res.push_back(vector<int>());
int currSize = q.size();
for (int i = 1; i <= currSize; ++i) {
auto node = q.front();
q.pop();
// 注意
res.back().push_back(node->val);
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
}
return res;
}
};
110 平衡二叉树
任意节点左右子树高度差<=1
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int height(TreeNode* root) {
if (root == NULL) {
return 0;
}else {
return max(height(root->left), height(root->right)) + 1;
}
}
bool isBalanced(TreeNode* root) {
if (root == NULL) {
return true;
} else {
return abs(height(root->left) - height(root->right)) <= 1 && isBalanced(root->left) && isBalanced(root->right);
}
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode* root) {
dfs(root);
return res;
}
bool res = true;
int dfs(TreeNode* node) {
if (node == nullptr) return 0;
int l = dfs(node->left), r = dfs(node->right);
if (abs(r - l) > 1) res = false;
return std::max(l, r) + 1;
}
};
230 二叉搜索树中第 k 小的元素
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
stack<TreeNode*> stack;
while (root != nullptr || stack.size() > 0) {
// 先找小的
while (root != nullptr) {
stack.push(root);
root = root->left;
}
root = stack.top();
stack.pop();
if (--k == 0) break;
root = root->right;
}
return root->val;
}
};
建树
后序最后一个节点是根节点-->确定左子树和右子树
106 中序 + 后序遍历构建二叉树
# Definition for a binary tree node.
class Solution:
def buildTree(self, inorder, postorder):
# 使用哈希表存储中序遍历数组的值和对应的索引
map = {val: idx for idx, val in enumerate(inorder)}
# 开始递归构建树
return self.dfs(0, len(inorder) - 1, 0, len(postorder) - 1, inorder, postorder, map)
def dfs(self, in_left, in_right, post_left, post_right, inorder, postorder, map):
# 如果中序遍历的左边界大于右边界,返回空节点
if in_left > in_right:
return None
# 创建根节点,值为后序遍历的最后一个元素
node = TreeNode(postorder[post_right])
# 获取根节点在中序遍历中的索引
in_index = map[postorder[post_right]]
# 计算左子树节点个数
left_cnt = in_index - in_left
# 递归构建左右子树
node.left = self.dfs(in_left, in_index - 1, post_left, post_left + left_cnt - 1, inorder, postorder, map)
node.right = self.dfs(in_index + 1, in_right, post_left + left_cnt, post_right - 1, inorder, postorder, map)
# 返回根节点
return node