代码随想录算法训练营第17天| Leetcode 110.平衡二叉树、257.二叉树的所有路径、404.左叶子之和

目录

Leetcode 110.平衡二叉树

Leetcode 257.二叉树的所有路径

Leetcode 404.左叶子之和


Leetcode 110.平衡二叉树

题目链接:Leetcode 110.平衡二叉树

题目描述:给定一个二叉树,判断它是否是高度平衡的二叉树。本题中,一棵高度平衡二叉树定义为:一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。

思路:由于本题是比较左右子树高度差,因此使用后序遍历更合适。分别求出其左右子树的高度,然后如果差值小于等于1,则返回当前二叉树的高度,否则返回-1,表示已经不是二叉平衡树了。

代码如下:(递归法)

class Solution {
public:
    int getHeight(TreeNode* node) {
        if (node == nullptr)
            return 0;
        int leftheight = getHeight(node->left);
        if (leftheight == -1)
            return -1;
        int rightHeight = getHeight(node->right);
        if (rightHeight == -1)
            return -1;
        return abs(leftheight - rightHeight) > 1
                   ? -1
                   : 1 + max(leftheight, rightHeight);
    }
    bool isBalanced(TreeNode* root) {
        return getHeight(root) == -1 ? false : true;
    }
};

迭代法思路是(1)先定义一个函数,利用一个栈模拟的后序遍历求出每个点的高度,(2)再用一个栈来模拟后序遍历,遍历每一个节点的时候,再去判断左右孩子的高度是否符合。这里我们发现,迭代法的代码用到了两个栈,而且细节很多,还包括了回溯的思想,稍有不慎就可能漏掉某些细节,然后debug很长时间。所以递归还是很香的hhh。

代码如下:(迭代法)

class Solution {
public:
    int getDepth(TreeNode* node) { //将每个节点高度求出来
        stack<TreeNode*> st;
        int depth = 0, result = 0;
        if (node != nullptr)
            st.push(node);
        while (!st.empty()) {
            TreeNode* node = st.top();
            if (node != nullptr) {
                st.pop();
                st.push(node);
                st.push(nullptr);
                depth++;
                if (node->left)
                    st.push(node->left);
                if (node->right)
                    st.push(node->right);
            } else {
                st.pop();
                node = st.top();
                st.pop();
                depth--; //回溯
            }
            result = max(result, depth);
        }
        return result;
    }
    bool isBalanced(TreeNode* root) {
        stack<TreeNode*> st;
        if (root == nullptr)
            return true;
        st.push(root);
        while (!st.empty()) { //比较左右子树高度差
            TreeNode* node = st.top();
            st.pop();
            if (abs(getDepth(node->left) - getDepth(node->right)) > 1)
                return false;
            if (node->right)
                st.push(node->right);
            if (node->left)
                st.push(node->left);
        }
        return true;
    }
};

Leetcode 257.二叉树的所有路径

题目链接:Leetcode 257.二叉树的所有路径

题目描述:给定一个二叉树,返回所有从根节点到叶子节点的路径。说明: 叶子节点是指没有子节点的节点。

思路:由于这道题需要求出根节点到叶子节点的所有路径,是从上到下的,因此前序遍历比较适合。这道题还是涉及到回溯,每次找到一个路径之后需要回退一个节点,再去寻找另一个路径。

代码如下:(递归法)

class Solution {
public:
    void travalsal(TreeNode* cur, vector<int>& path, vector<string>& result) {
        path.push_back(cur->val); //中,因为最后一个节点也要加入到路径中,因此先加入根节点
        //判断是否是叶子节点
        if (cur->left == nullptr && cur->right == nullptr) {
            string sPath;
            for (int i = 0; i < path.size() - 1; i++) {
                sPath += to_string(path[i]);
                sPath += "->";
            }
            sPath += to_string(path[path.size() - 1]);
            result.push_back(sPath);
            return;
        }
        if (cur->left) {
            travalsal(cur->left,path,result); //向下递归
            path.pop_back();      //递归之后要将路径恢复原状
        }
        if (cur->right) {
            travalsal(cur->right,path,result);
            path.pop_back();
        }
    }
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<int> path;
        vector<string> result;
        if (root == nullptr)
            return result;
        travalsal(root, path, result);
        return result;
    }
};

(迭代法)

class Solution {
public:
    vector<string> binaryTreePaths(TreeNode* root) {
        stack<TreeNode*> treest; // 保存树的遍历节点
        stack<string> pathst;    // 保存遍历路径的节点
        vector<string> result;   // 保存最终路径集合
        if (root == nullptr)
            return result;
        treest.push(root);
        pathst.push(to_string(root->val));
        while (!treest.empty()) {
            TreeNode* node = treest.top(); treest.pop(); //中
            string path = pathst.top(); pathst.pop(); //取出路径
            //判断是否是叶子节点
            if (node->left == nullptr && node->right == nullptr) {
                result.push_back(path);
            }
            if (node->right) { //右
                treest.push(node->right);
                pathst.push(path + "->" + to_string(node->right->val));
            }
            if (node->left) { //左
                treest.push(node->left);
                pathst.push(path + "->" + to_string(node->left->val));
            }
        }
        return result;
    }
};

PS:第二道题不是很理解,只是跟着题解的思路捋了一遍,明天抽空再看看。

Leetcode 404.左叶子之和

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

题目描述:计算给定二叉树的所有左叶子之和。

思路:首先要注意这道题是判断左叶子而不是左侧节点,根据题干的样例我们可以知道:如果A的左孩子不为空,且A的左孩子是叶子节点(左右孩子为空),则A的左孩子为左叶子。

代码如下:(递归法)

class Solution {
public:
    int sumOfLeftLeaves(TreeNode* root) {
        if (root == nullptr)
            return 0;
        if (root->left == nullptr && root->right == nullptr)
            return 0; //不写也可以,就是多一层递归
        int leftval = sumOfLeftLeaves(root->left);
        //找左叶子
        if (root->left && root->left->left == nullptr &&
            root->left->right == nullptr) {
            leftval += root->left->val;
        }
        int rightval = sumOfLeftLeaves(root->right);
        return leftval + rightval;
    }
};

(迭代法)

class Solution {
public:
    int sumOfLeftLeaves(TreeNode* root) {
        stack<TreeNode*> st;
        if (root == nullptr)
            return 0;
        st.push(root);
        int result = 0;
        while (!st.empty()) {
            TreeNode* node = st.top();
            st.pop();
            if (node->left != nullptr && node->left->left == nullptr &&
                node->left->right == nullptr) {
                result += node->left->val;
            }
            if (node->right)//右
                st.push(node->right);
            if (node->left)//左
                st.push(node->left);
        }
        return result;
    }
};

总结:今天的题感觉理解上难度提升了,不过还是跟着题解的思路捋了下来。

最后,如果文章有错误,请在评论区或私信指出,让我们共同进步!

  • 10
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值