【刷题】day02-根据中序和后序重建二叉树、判断两棵树相等、恢复二叉搜索树、判断是不是有效二叉搜索树

本文详细解析了四种经典的二叉树算法:从后序与中序遍历构建二叉树、判断二叉树是否相同、恢复二叉搜索树及验证二叉搜索树的有效性。通过递归方式实现这些算法,并提供了完整的C++代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[编程题]construct-binary-tree-from-inorder-and-postorder-traversal
热度指数:7492时间限制:1秒空间限制:32768K
算法知识视频讲解

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.
本题来自leetcode,题目为从中序遍历和后序遍历重建二叉树
题目内容是:
给定一个树的顺序和后序遍历,构造二叉树。
注:您可以假设树中不存在重复。
算法思想:我们可以在后序遍历的最后一个结点找到我们的根节点,然后在中序遍历中找到根结点的位置,中序遍历的特点就是根的左边就是左子树的结点,右边就是右子树的结点。后序遍历的左子树结点相邻,右子树结点相邻。
具体算法是,我们先在后序遍历中找到根结点,然后构造根结点,我们根据根据根结点的值将中序遍历分为两部分,再根据中序遍历两部分的大小将后序遍历分为两部分,然后递归创建二叉树。
代码如下:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
        if (inorder.empty())
            return NULL;
        int key = postorder[postorder.size() - 1];
        TreeNode* pRoot = new TreeNode(key);
        vector<int>::iterator iter = find(inorder.begin(), inorder.end(), key);
        vector<int> leftin = vector<int>(inorder.begin(), iter);
        vector<int> rightin = vector<int>(iter + 1, inorder.end());
        int left = leftin.size();
        int right = rightin.size();
        if (left > 0)
        {
            vector<int> leftpo = vector<int>(postorder.begin(), postorder.begin() + left);
            pRoot->left = buildTree(leftin, leftpo);
        }
        if (right > 0)
        {
            vector<int> rightpo = vector<int>(postorder.begin() + left, postorder.begin() + left + right);
            pRoot->right = buildTree(rightin, rightpo);
        }
        return pRoot;
    }
};

[编程题]same-tree
热度指数:10587时间限制:1秒空间限制:32768K
算法知识视频讲解

Given two binary trees, write a function to check if they are equal or not.

Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
题目解释;
给定两棵二叉树,写一个函数来检查它们是否相等。
如果两个二叉树在结构上相同且节点具有相同的值,则它们被认为是相等的。
算法说明:先判断两棵树是不是同时为空,如果同时为空,返回一个true,然后判断一个为空一个不为空的情况,返回一个false,再判断两个的值是不是相等,不相等返回一个false,然后递归判断两棵树的左子树是否相等,右子树是否相等。
代码如下:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
 public:
     bool isSameTree(TreeNode *p, TreeNode *q) {
         if (p == NULL && q == NULL)
             return true;
         else if (p == NULL || q == NULL)
             return false;
         else if (p->val != q->val)
             return false;
         return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
     }
 };

注意:判断两个值相等的时候,只能判断不相等,因为当前值相等不一定两棵树就相等,当前结点值相等并不能保证它的子树的结点相等,反之,要是当前结点值不相等,则这两棵树一定不相等。

[编程题]recover-binary-search-tree
热度指数:6784时间限制:1秒空间限制:32768K
算法知识视频讲解

Two elements of a binary search tree (BST) are swapped by mistake.

Recover the tree without changing its structure.

Note:
A solution using O(n ) space is pretty straight forward. Could you devise a constant space solution?

confused what”{1,#,2,3}”means? > read more on how binary tree is serialized on OJ.

OJ’s Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where ‘#’ signifies a path terminator where no node exists below.

Here’s an example:

1
/ \
2 3
/
4
\
5
The above binary tree is serialized as”{1,2,3,#,#,4,#,#,5}”.
题目解释:
二进制搜索树(BST)的两个元素被错误地交换。
在不改变结构的情况下恢复树。
注:
使用O(n)空间的解决方案非常直接。你能设计出一个恒定的空间解决方案吗?
混淆了“{ 1,γ,2,3}”是什么意思?请参阅更多关于如何在OJ上序列化二叉树。
OJ的二叉树序列化:
二叉树的序列化遵循一个级别顺序遍历,其中’y’表示不存在节点的路径终止符。
算法:
我们知道二叉搜索树有一个特点,它的中序遍历是递增有序的,所以我们这里就利用这一个特点,对这个错误的二叉搜索树进行中序遍历,如果是错误的那么它的中序遍历就不是有序的,所以我们遍历的时候将这棵二叉树的结点和值分别用一个容器保存起来,对值的容器进行排序,然后再把排序后的值赋给结点的中序遍历序列。
代码如下:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
 class Solution {
 public:
     void Inorder(TreeNode* root, vector<int> &val, vector<TreeNode*> &node)
     {
         if (root)
         {
             Inorder(root->left,val,node);
             val.push_back(root->val);
             node.push_back(root);
             Inorder(root->right, val, node);
         }
     }
     void recoverTree(TreeNode *root) {
         vector<int> val;
         vector<TreeNode*> node;
         Inorder(root,val, node);
         sort(val.begin(), val.end());
         for (int i = 0; i < val.size(); i++)
         {
             node[i]->val = val[i];
         }
     }
 };

[编程题]validate-binary-search-tree
热度指数:8491时间限制:1秒空间限制:32768K
算法知识视频讲解

Given a binary tree, determine if it is a valid binary search tree (BST).

Assume a BST is defined as follows:

The left subtree of a node contains only nodes with keys less than the node’s key.
The right subtree of a node contains only nodes with keys greater than the node’s key.
Both the left and right subtrees must also be binary search trees.

confused what”{1,#,2,3}”means? > read more on how binary tree is serialized on OJ.

OJ’s Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where ‘#’ signifies a path terminator where no node exists below.

Here’s an example:

1
/ \
2 3
/
4
\
5
The above binary tree is serialized as”{1,2,3,#,#,4,#,#,5}”.
题目解释:
给定一棵二叉树,确定它是否是一个有效的二叉搜索树(BST)。
假设BST定义如下:
节点的左子树只包含比节点的键少的节点。
节点的右子树只包含比节点的键大的节点。
左、右子树也必须是二叉搜索树。
混淆了“{ 1,#,2,3}”是什么意思?请参阅更多关于如何在OJ上序列化二叉树。
OJ的二叉树序列化:
二叉树的序列化遵循一个级别顺序遍历,其中’y’表示不存在节点的路径终止符。
算法思想:这里还是利用中序遍历思想。我们知道一个有效的二叉搜索树的中序遍历是单调递增有序的,所以它的中序遍历的前一个值一定是小于后面一个的,我们用一个变量记下前一个结点,然后用前一个结点的值和当前结点的值进行比较,如果满足要求就证明是有效的,一旦遇到前一个结点大于或者等于当前结点的就是无效的二叉搜索树。
代码如下:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
 public:
     bool isValid = true;
     TreeNode* pre=NULL;
     void Inorder(TreeNode* root)
     {
         if (root)
         {
             Inorder(root->left);
             if (pre && pre->val >= root->val) isValid = false;
             pre = root;
             Inorder(root->right);
         }

     }
     bool isValidBST(TreeNode *root) {
         Inorder(root);
         return isValid;
     }
 };
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值