class Solution {
public:
TreeNode* Convert(TreeNode* pRootOfTree) {
if(pRootOfTree == nullptr) return nullptr;
vector<TreeNode*> cur = traversal(pRootOfTree);
return cur[0];
}
// 这道题需要用到「分解问题」的思维,想把整棵链表,可以先把左右子树变成链表
//然后把 root.val 接在中间,这样就形成了整棵 BST 的环形链表
vector<TreeNode*> traversal(TreeNode* pRootOfTree){
if(pRootOfTree == nullptr) return {nullptr, nullptr};
vector<TreeNode*> left = traversal(pRootOfTree->left);
vector<TreeNode*> right = traversal(pRootOfTree->right);
pRootOfTree->left = left[1];
if(left[1] != nullptr) left[1]->right = pRootOfTree;
pRootOfTree->right = right[0];
if(right[0] != nullptr) right[0]->left = pRootOfTree;
if(left[0] == nullptr) left[0] = pRootOfTree;
if(right[1] == nullptr) right[1] = pRootOfTree;
return {left[0], right[1]};
}
};
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
int ans = nodeHeight(pRoot);
return ans == -1 ? false : true;
}
int nodeHeight(TreeNode* cur){
if(cur == nullptr) return 0;
int leftHeight = nodeHeight(cur->left); //注意!!! 1不能加这里!!!
if(leftHeight == -1) return -1; //必须加上,否者会将一些非平衡树误判为平衡树
int rightHeight = nodeHeight(cur->right);
if(rightHeight == -1) return -1; 必须加上,否者会将一些非平衡树误判为平衡树
//注意!!!需要+1 !!!
return abs(leftHeight - rightHeight) > 1 ? -1 : max(leftHeight, rightHeight) + 1;
}
};
class Solution {
public:
TreeLinkNode* GetNext(TreeLinkNode* pNode) {
if(pNode == nullptr) return nullptr;
if(pNode->right != nullptr){
pNode = pNode->right;
while(pNode->left != nullptr)
pNode = pNode->left;
return pNode;
}
else{
while(pNode->next != nullptr && pNode->next->left != pNode)
pNode = pNode->next;
if(pNode->next != nullptr) return pNode->next;
else return nullptr;
}
}
};
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int> > res;
if(pRoot == nullptr) return res;
queue<TreeNode*> que;
que.push(pRoot);
while(!que.empty()){
int que_size = que.size();
vector<int> temp;
for(int i = 0; i < que_size; i++){
TreeNode* cur = que.front();
que.pop(); temp.push_back(cur->val);
if(cur->left != nullptr) que.push(cur->left);
if(cur->right != nullptr) que.push(cur->right);
}
res.push_back(temp);
temp.clear();
}
return res;
}
};
class Solution {
public:
int lowestCommonAncestor(TreeNode* root, int o1, int o2) {
if(root == nullptr) return -1;
// 后序遍历
int left = lowestCommonAncestor(root->left, o1, o2);
int right = lowestCommonAncestor(root->right, o1, o2);
if(root->val == o1 || root->val == o2 || (left != -1 && right != -1)) return root->val;
else if(left != -1) return left;
else if(right != -1) return right;
else return -1;
}
};
class Solution {
public:
int lowestCommonAncestor(TreeNode* root, int p, int q) {
if(root == nullptr) return -1;
if(root->val >= min(p,q) && root->val <= max(p,q)) return root->val;
if(root->val > max(p,q)) {
int left = lowestCommonAncestor(root->left, p, q);
if(left != -1) return left;
}
if(root->val < min(p,q)) {
int right = lowestCommonAncestor(root->right, p, q);
if(right != -1) return right;
}
return -1;
}
};