day17 | 二叉树part4

110平衡二叉树难度最大
剩下的两个就是朴素dfs

110. 平衡二叉树

不和条件返回-1。不然返回最大高度

class Solution {
public:
    // 不和条件了就是-1
    bool isBalanced(TreeNode* root) {
        return getHeight(root, 0) != -1;
    }

    int getHeight(TreeNode* root, int height)
    {
        if (root == nullptr) return height;
        int leftHeight = getHeight(root->left, height + 1);
        int rightHeight = getHeight(root->right, height + 1);
        if (leftHeight == -1 || rightHeight == -1) return -1;
        return abs(leftHeight - rightHeight) > 1 ? -1 : max(leftHeight, rightHeight);
    }
};

257. 二叉树的所有路径

class Solution {
public:
    vector<string> res;

    vector<string> binaryTreePaths(TreeNode* root) {
        dfs(root, "");
        return res;
    }

    void dfs(TreeNode *root, string s)
    {
        if (root == nullptr)
        {
            return;
        }
        if (root->left == nullptr && root->right == nullptr)
        {
            s += "->" + to_string(root->val);
            res.push_back(s.substr(2, s.size() - 2));
            return;
        }
        dfs(root->left, s + "->" + to_string(root->val));
        dfs(root->right, s + "->" + to_string(root->val));
    }
};

404. 左叶子之和

class Solution {
public:
    int res = 0;
    int sumOfLeftLeaves(TreeNode* root) {
        dfs(root);
        return res;
    }

    // 如何确定左节点?
    void dfs(TreeNode* root)
    {
        if (root == nullptr) return;
        if (root->left && root->left->left == nullptr && root->left->right == nullptr)
        {
            res += root->left->val;
        }
        dfs(root->left);
        dfs(root->right);
    }
};
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇