算法记录Day 17 | 二叉树part04

72 阅读1分钟

算法记录Day 17 | 二叉树part04

LeetCode 110.平衡二叉树

题目链接:leetcode.cn/problems/ba…

题解
class Solution {
   public:
    // 后序遍历,返回子树高度
    bool isBalanced(TreeNode* root) { return recur(root) != -1; }

    int recur(TreeNode* root) {
        // 越过叶结点,返回0
        if (root == nullptr) {
            return 0;
        }
        int left = recur(root->left);
        if (left == -1) {
            return -1;
        }
        int right = recur(root->right);
        if (right == -1) {
            return -1;
        }
        // 深度差<=1,返回当前子树深度
        if (abs(left - right) < 2) {
            return max110(left, right) + 1;
        } else {
            return -1;
        }
        return 0;
    }

    int max110(int a, int b) {
        if (a > b) {
            return a;
        }
        return b;
    }
};

LeetCode 257. 二叉树的所有路径

题目链接:leetcode.cn/problems/bi…

题解
class Solution {
   public:
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> res;
        string path;
        if (root == nullptr) {
            return res;
        }
        traversal(root, path, &res);
        return res;
    }
    void traversal(TreeNode* root, string path, vector<string>* res) {
        path += to_string(root->val);
        if (root->left == nullptr && root->right == nullptr) {
            res->push_back(path);
        }
        // 回溯就隐藏在traversal(cur->left, path + "->", result);中的 path +
        // "->"。 每次函数调用完,path依然是没有加上"->" 的,这就是回溯了。
        if (root->left) {
            traversal(root->left, path + "->", res);
        }
        if (root->right) {
            traversal(root->right, path + "->", res);
        }
        return;
    }
};

LeetCode 404. 左叶子之和

题目链接:404. 左叶子之和

题解
class Solution {
   public:
    int sum = 0;
    int sumOfLeftLeaves(TreeNode* root) {
        dfs(root);
        return sum;
    }
    void dfs(TreeNode* root) {
        if (root == nullptr) {
            return;
        }
        // 是左叶子结点
        if (root->left && !root->left->left && !root->left->right) {
            sum += root->left->val;
        }
        dfs(root->left);
        dfs(root->right);
    }
};