算法刷题Day18 找树左下角的值+路径总和+从中序与后序遍历构造二叉树

Day 18 二叉树

513. 找树左下角的值

一眼层序遍历

层序遍历

class Solution {
public:
    int findBottomLeftValue(TreeNode* root) {
        if (!root) return -1;
        queue<TreeNode*> que;
        que.push(root);
        int target;
        
        while (!que.empty())
        {
            int len = que.size();
            for (int i = 0; i < len; ++i)
            {
                TreeNode *cur = que.front();
                que.pop();
                if (i == 0)
                {
                    target = cur->val;
                }
                if (cur->left) que.push(cur->left);
                if (cur->right) que.push(cur->right);
            }
        }

        return target;
    }
};

112. 路径总和

回溯的方法

class Solution {
    int sum;
    bool flag;

    void helper(TreeNode *root, int targetSum)
    {
        if (!root) return;
        sum += root->val;
        if (!root->left && !root->right) 
        {
            if (sum == targetSum)
            {
                flag = true;
            }
        }
        else
        {
            if (root->left) helper(root->left, targetSum);
            if (root->right) helper(root->right, targetSum);
        }
        sum -= root->val;
    }

public:
    bool hasPathSum(TreeNode* root, int targetSum) {
        sum = 0;
        flag = false;
        helper(root, targetSum);
        return flag;
    }
};

106. 从中序与后序遍历序列构造二叉树

《剑指Offer》有“从前序与中序遍历序列构造二叉树”的讲解,这里把前序换成后序,应该是差不多的思路

class Solution {
    TreeNode *build(
        vector<int> &inorder, int startInorder, int endInorder,
        vector<int> &postorder, int startPostorder, int endPostorder)
    {
        if (startInorder >= endInorder) return nullptr;
        int targetVal = postorder[endPostorder - 1], idx = -1;
        TreeNode *root = new TreeNode(targetVal);
        for (int i = startInorder; i < endInorder; ++i)
        {
            if (inorder[i] == targetVal)
            {
                idx = i;
            }
        }
        int leftLen = idx - startInorder;
        root->left = build(inorder, startInorder, idx, postorder, startPostorder, startPostorder + leftLen);
        root->right = build(inorder, idx + 1, endInorder, postorder, startPostorder + leftLen, endPostorder - 1);
        return root;
    }

public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        TreeNode *root = build(inorder, 0, inorder.size(), postorder, 0, postorder.size());
        return root;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值