1.Preorder,Inorder,Postorder
class Solution {
//recursive solution
//preorder
private:
void preOrder(TreeNode* cur,vector<int> &res){
if(cur==NULL) return;
res.push_back(cur->val);
preOrder(cur->left,res);
preOrder(cur->right,res);
}
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
preOrder(root,res);
return res;
}
};
/** Iterative solution for inorder
* 先走到最左边,然后对点进行操作,再去右边
*/
vector<int> inorderTraversal(TreeNode* root) {
stack<TreeNode*> search;
vector<int> res;
TreeNode* cur=root;
while(cur!=NULL||!search.empty()){
while(cur){
search.push(cur);
cur=cur->left;
}
cur=search.top();
search.pop();
res.push_back(cur->val);
cur=cur->right;
}
return res;
}
2.Populationg next right pointers in each node II
class Solution {
public:
void connect(TreeLinkNode *root) {
TreeLinkNode* cur=root;
TreeLinkNode* head=NULL;//head of next level
TreeLinkNode* prev=NULL;//previous node
while(cur!=NULL){
while(cur!=NULL){
if(cur->left){
if(prev){
prev->next=cur->left;
}else{
head=cur->left;
}
prev=cur->left;
}
if(cur->right){
if(prev){
prev->next=cur->right;
}else{
head=cur->right;
}
prev=cur->right;
}
cur=cur->next;
}
cur=head;
head=NULL;
prev=NULL;
}
}
};
3.lowest common ancestor of binary tree
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root==NULL||root==p||root==q)
return root;
TreeNode* parent1=lowestCommonAncestor(root->left,p,q);
TreeNode* parent2=lowestCommonAncestor(root->right,p,q);
if(parent1&&parent2)
return root;
else
return parent1? parent1:parent2;
}
};
4.serialize and deserialize binary tree
class Codec {
/**总结下 istringstream和ostringstream
* ostringstream 用来构造string,操作符 << 表示向其中写入对象
* istringstream 用来从string中读取对象,以空格为间断
*/
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
ostringstream out;
serial(root,out);
return out.str();
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
istringstream in(data);
return deserial(in);
}
private:
void serial(TreeNode* cur,ostringstream &out){
if(cur){
out<<cur->val<<' ';
serial(cur->left,out);
serial(cur->right,out);
}else{
out<<"# ";
}
}
TreeNode* deserial(istringstream &in){
string cur;
in>>cur;
if(cur=="#")
return nullptr;
else{
TreeNode* temp=new TreeNode(stoi(cur));
temp->left=deserial(in);
temp->right=deserial(in);
return temp;
}
}
};