代码随想录Day 16: lc513, 112, 113, 106

513. Find Bottom Left Tree Value

思路:

  • 递归: 用中序遍历确保左节点最先visit,再记录最大深度
  • BFS
// 递归
class Solution {
public:
    int depth = INT_MIN;
    int res = 0;
    void traverse(TreeNode* root, int d) {
        if (!root) {
            return;
        }
        traverse(root->left, d + 1);
        if (!root->left && !root->right) {
            if (d > depth) {
                res = root->val;
                depth = d;
            }
            return;
        }
        traverse(root->right, d + 1);
    }
    int findBottomLeftValue(TreeNode* root) {
        traverse(root, 0);
        return res;
    }
};

112. Path Sum

  • 如果需要搜索整棵二叉树且不用处理递归返回值,递归函数就不要返回值。(113.路径总和ii
  • 如果需要搜索整棵二叉树且需要处理递归返回值,递归函数就需要返回值。 (236. 二叉树的最近公共祖先中介绍)
  • 如果要搜索其中一条符合条件的路径,那么递归一定需要返回值,因为遇到符合条件的路径了就要及时返回。

106. Construct Binary Tree from Inorder and Postorder Traversal

class Solution {
public:
    TreeNode* helper(int postend, int instart, int inend, vector<int>&in, vector<int>&post) {
        if (postend < 0 || instart > inend) {
            return NULL;
        }
        TreeNode* root = new TreeNode(post[postend]);
        int idx = 0;
        for (int i = instart; i <= inend; i++) {
            if (in[i] == post[postend]) {
                idx = i;
                break;
            }
        }
        root->left = helper(postend - (inend - idx + 1), instart, idx - 1, in, post);
        root->right = helper(postend - 1, idx + 1, inend, in, post);
        return root;
    }

    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        return helper(postorder.size() - 1, 0, inorder.size() - 1, inorder, postorder);
    }
};

105. Construct Binary Tree from Preorder and Inorder Traversal

class Solution {
public:
    TreeNode* helper(int prestart, int instart, int inend, vector<int>&pre, vector<int>&in) {
        if (prestart >= pre.size() || instart > inend) {
            return NULL;
        }
        TreeNode* root = new TreeNode(pre[prestart]);
        int idx = 0;
        for (int i = instart; i <= inend; i++) {
            if (in[i] == pre[prestart]) {
                idx = i;
                break;
            }
        }
        root->left = helper(prestart + 1, instart, idx - 1, pre, in);
        root->right = helper(prestart + idx - instart + 1, idx + 1, inend, pre, in);
        return root;
    }
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        return helper(0, 0, inorder.size() - 1, preorder, inorder);
    }
};

前序和后序不能唯一确定一棵二叉树,因为没有中序遍历无法确定左右部分,无法分割。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值