190. Reverse Bits\331. Verify Preorder Serialization of a Binary Tree

来源:互联网 发布:qsv视频格式转换器mac 编辑:程序博客网 时间:2024/06/16 02:49

  • Reverse Bits
    • description
    • implementation
  • Verify Preorder Serialization of a Binary Tree
    • description
    • implementation

190. Reverse Bits

description

Reverse bits of a given 32 bits unsigned integer.

For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).

Follow up:
If this function is called many times, how would you optimize it?

Related problem: Reverse Integer

My algorithm shows below:
1 extract the ind bit and 31-ind bit from n
2 set ind and 31-ind bit to zero
3 exchange bit from step 1 to set the bit, go to step 1 if ind < 16
4 return result n

implementation

iterative version:

class Solution {public:    uint32_t reverseBits(uint32_t n) {        int ind = 0;        while(ind < 16) {            uint32_t t1 = (n >> ind)&1;            uint32_t t2 = (n >> (31-ind)) & 1;            n = (~(1 << (31-ind))) & n;            n = (~(1 << ind)) & n;            n |= t1 << (31-ind);             n |= t2 << ind;            ind++;        }        return n;    }};

recursive version:

class Solution {public:    uint32_t recursiveReverse(uint32_t n, int stt, int lst) {        if(stt == lst) return 0;        if(stt + 1 == lst)             return (((n >> stt) & 1) << lst) | (((n >> lst) & 1) << stt);        int half = (stt+lst) >> 1;        uint32_t left_part = recursiveReverse(n >> (half+1) << stt, stt, half);        uint32_t right_part = recursiveReverse(n << (31 - half) >> (31 - lst), half+1, lst);        return left_part | right_part;    }    uint32_t reverseBits(uint32_t n) {        return recursiveReverse(n, 0, 31);    }};

331. Verify Preorder Serialization of a Binary Tree

description

One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-null node, we record the node’s value. If it is a null node, we record using a sentinel value such as #.

     _9_    /   \   3     2  / \   / \ 4   1  #  6/ \ / \   / \# # # #   # #

For example, the above binary tree can be serialized to the string “9,3,4,#,#,1,#,#,2,#,6,#,#”, where # represents a null node.

Given a string of comma separated values, verify whether it is a correct preorder traversal serialization of a binary tree. Find an algorithm without reconstructing the tree.

Each comma separated value in the string must be either an integer or a character ‘#’ representing null pointer.

You may assume that the input format is always valid, for example it could never contain two consecutive commas such as “1,,3”.

Example 1:

"9,3,4,#,#,1,#,#,2,#,6,#,#"Return true

Example 2:

"1,#"Return false

Example 3:

"9,#,#,1"Return false

The thought of this algorithm:

I find that two consecutive ‘#’ will be a root, I replace ‘1##’ with a ‘#’. In this way, I can eliminate the sub-tree. Finally, I just compare the stack result with ‘#’ to judge whether it’s pre-order sequence.

The exact algorithm steps shows below:
1 if str[i] is digit, push into stack until str[++i] is not digit.
if str[i] is ‘#’, judge the stack top two element, if ‘d#’, then replace it with ‘#’. Otherwise break. Insert ‘#’ into stack. Do it iterative.
2 if stack with size 1 and top element is ‘#’, return true. Otherwise false.

implementation

class Solution {public:    bool isValidSerialization(string preorder) {        stack<int> seq;        int len = preorder.size();        for(int i = 0; i < len; ) {             if(preorder[i] == '#') {                if(seq.empty() || seq.top() != 0)                    seq.push(0);                else { // insert a "#"                    while(true) {                        if(seq.empty()) break;                        int tp = seq.top(); // 0                        if(tp == 1) break;  // meet 1                         seq.pop();                        if(seq.empty()) return false;                         tp = seq.top();                            if(tp == 1)  seq.pop();                    }                    seq.push(0);                }                    i++;            }                else if(preorder[i] >= '0' && preorder[i] <= '9') {                seq.push(1);                i++;                while(i < len && preorder[i] >= '0' && preorder[i] <= '9') i++;            }            else i++;        }            return seq.size() == 1 && seq.top() == 0;    }};
0 0
原创粉丝点击