解题思路:
- 是否可以通过 遍历 \color{OrangeRed}遍历 遍历一遍二叉树得到答案? 如果可以,用一个traverse函数配合外部变量实现
- 是否可以定义一个递归函数,通过子问题(子树)的答案推导出原问题的答案? 分解问题 \color{OrangeRed}分解问题 分解问题
- 不管哪种模式,需要思考:如果单独抽出一个节点,它需要做什么事情,需要在什么时候(前/中/后序位置)做
完全二叉树:
- 定义:在完全二叉树中,除了最底层节点可能没填满之外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层的最左边,若最底层为h层,则该层包含 1 − p o w ( 2 , h − 1 ) \color{OrangeRed}1 - pow(2, h-1) 1−pow(2,h−1) 个节点
- 完全二叉树有 2 d − 1 \color{OrangeRed}2^d - 1 2d−1个节点
Leetcode 222. Count Complete Tree Nodes
class Solution {
public:
int countNodes(TreeNode* root) {
// Time Complexity: O(log n x log n)
if (root == nullptr)
{
return 0;
}
TreeNode* l = root->left;
TreeNode* r = root->right;
int l_depth = 0, r_depth = 0;
while (l)
{
l_depth ++;
l = l->left;
}
while (r)
{
r_depth ++;
r = r->right;
}
if (r_depth == l_depth)
{
return (2 << l_depth) - 1; // (2 << 1) = 2^2
}
return 1 + countNodes(root->left) + countNodes(root->right);
}
};
Leetcode 110. Balanced Binary Tree
class Solution {
public:
// -1 means it's already not a balanced tree
int depth(TreeNode* root)
{
if (root == nullptr)
{
return 0;
}
int l = depth(root->left);
if (l == -1) return -1;
int r = depth(root->right);
if (r == -1) return -1;
return abs(l - r) > 1 ? -1 : 1 + max(l, r);
}
bool isBalanced(TreeNode* root) {
return depth(root) != -1;
}
};
- 二叉树节点的深度:指从根节点到该节点的最长简单路径边的条数。 p r e o r d e r \color{OrangeRed} preorder preorder
- 二叉树节点的高度:指从该节点到叶子节点的最长简单路径边的条数。 p o s t o r d e r \color{OrangeRed} postorder postorder
Leetcode 257 Binary Tree Path
B a c k t r a c k i n g : \color{OrangeRed} Backtracking: Backtracking: the use of string s, do not path by reference, otherwise it’s not backtracking
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string<