forked from changqing16/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTree.cpp
More file actions
61 lines (54 loc) · 1.43 KB
/
Tree.cpp
File metadata and controls
61 lines (54 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <iostream>
#include <vector>
#include<cctype>
using namespace std;
//Definition for a binary tree node.
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
TreeNode *sortedArrayToBST(vector<int> &nums);
TreeNode *bulid(vector<int> &nums, int position, int size);
bool isPalindrome(string s)
{
for (int i = 0, j = s.size() - 1; i < j; i++, j--)
{ // Move 2 pointers from each end until they collide
while (isalnum(s[i]) == false && i < j)
i++; // Increment left pointer if not alphanumeric
while (isalnum(s[j]) == false && i < j)
j--; // Decrement right pointer if no alphanumeric
if (toupper(s[i]) != toupper(s[j]))
return false; // Exit and return error if not match
}
return true;
}
int main()
{
int n, temp;
cin >> n;
vector<int> nums;
while (n--)
{
cin >> temp;
nums.push_back(temp);
}
sortedArrayToBST(nums);
}
TreeNode *sortedArrayToBST(vector<int> &nums)
{
int position = nums.size();
return bulid(nums, position / 2, position);
}
TreeNode *bulid(vector<int> &nums, int position, int size)
{
TreeNode *node = new TreeNode(nums.at(position));
if (size == 0)
return NULL;
size = size / 2;
node->left = bulid(nums, position - size, size);
node->right = bulid(nums, position + size, size);
return node;
}