Leetcode1008. 先序遍历构造二叉树

题目

返回与给定先序遍历 preorder 相匹配的二叉搜索树(binary search tree)的根结点。

(回想一下,二叉搜索树是二叉树的一种,其每个节点都满足以下规则,对于 node.left 的任何后代,值总 < node.val,而 node.right 的任何后代,值总 > node.val。此外,先序遍历首先显示节点的值,然后遍历 node.left,接着遍历 node.right。)

示例:

输入:[8,5,1,7,10,12]
输出:[8,5,10,1,7,null,12]

提示:

1 <= preorder.length <= 100
先序 preorder 中的值是不同的。

C++解法

#include <iostream>
#include <vector>
#include <map>
#include <set>
using namespace std;
class Solution {
public:
    int bitwiseComplement(int N) {
        bool recognized = false;
        int num = N;
        for (int i = 0; i < 32; i++) {
            int shift = (1 << (32 - i - 1));
            if (!recognized) recognized = num & shift;
            if (recognized) num ^= shift;
        }
        if (!recognized) num = 1;
        return num;
    }
};

int main(int argc, const char * argv[]) {
    Solution solution;
    int i = 9;
    cout << solution.bitwiseComplement(5) << endl;
    cout << solution.bitwiseComplement(7) << endl;
    cout << solution.bitwiseComplement(10) << endl;
    cout << solution.bitwiseComplement(0) << endl;
    return 0;
}

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/construct-binary-search-tree-from-preorder-traversal

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容