/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<ListNode*> listOfDepth(TreeNode* tree) {
queue<TreeNode*>q;
q.push(tree);
vector<ListNode*>res;
while(!q.empty()) {
int n = q.size();
ListNode* head = new ListNode(-1);
ListNode* p = head;
while(n --) {
TreeNode* cur = q.front(); q.pop();
if(cur->left) {
q.push(cur->left);
}
if(cur->right) {
q.push(cur->right);
}
p->next = new ListNode(cur->val);
p = p->next;
}
res.push_back(head->next);
delete head;
}
return res;
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* dfs(vector<int>&nums, int l, int r) {
if(l > r) return NULL;
int mid = (l + r) >> 1;
TreeNode* head = new TreeNode(nums[mid]);
head->left = dfs(nums, l, mid - 1);
head->right = dfs(nums, mid + 1, r);
return head;
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
return dfs(nums, 0, nums.size() - 1);
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int getHeight(TreeNode* root) {
if(root == NULL) return 0;
int left = getHeight(root->left);
int right = getHeight(root->right);
return left > right ? left + 1 : right + 1;
}
bool isBalanced(TreeNode* root) {
if(root == NULL) return true;
if(abs(getHeight(root->left) - getHeight(root->right)) > 1) return false;
return isBalanced(root->left) && isBalanced(root->right);
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == NULL) return 0;
int left = maxDepth(root->left);
int right = maxDepth(root->right);
return left > right ? left + 1 : right + 1;
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int res;
void dfs(TreeNode* root, int &k) {
if(root == NULL) return;
dfs(root->right, k);
if(k == 0) return;
if(--k == 0) res = root->val;
dfs(root->left, k);
}
int kthLargest(TreeNode* root, int k) {
dfs(root, k);
return res;
}
};