Binary Tree - 2

解题思路:
  1. 是否可以通过 遍历 \color{OrangeRed}遍历 遍历一遍二叉树得到答案? 如果可以,用一个traverse函数配合外部变量实现
  2. 是否可以定义一个递归函数,通过子问题(子树)的答案推导出原问题的答案? 分解问题 \color{OrangeRed}分解问题 分解问题
  3. 不管哪种模式,需要思考:如果单独抽出一个节点,它需要做什么事情,需要在什么时候(前/中/后序位置)做
完全二叉树:
  1. 定义:在完全二叉树中,除了最底层节点可能没填满之外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层的最左边,若最底层为h层,则该层包含 1 − p o w ( 2 , h − 1 ) \color{OrangeRed}1 - pow(2, h-1) 1pow(2,h1) 个节点
  2. 完全二叉树有 2 d − 1 \color{OrangeRed}2^d - 1 2d1个节点
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;
    }
};
  1. 二叉树节点的深度:指从根节点到该节点的最长简单路径边的条数。 p r e o r d e r \color{OrangeRed} preorder preorder
  2. 二叉树节点的高度:指从该节点到叶子节点的最长简单路径边的条数。 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<
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值