Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1
/
2 5
/ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
解法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:
void flatten(TreeNode* root) {
TreeNode* p=nullptr;
stack<TreeNode*> st;
st.push(root);
TreeNode *last=nullptr;
while(!st.empty()){
p=st.top();
st.pop();
if(p==nullptr){
continue;
}
st.push(p->right);
st.push(p->left);
if(last != nullptr) {
last->right = p;
}
last=p;
last->left=nullptr;
}
}
};
解法2:
若root的左结点非空,将root左子树的最右根结点的右指针指向root的右子树,root的右结点指针指向左结点,root变为右子结点;否则,继续往右走。
class Solution {
public:
void flatten(TreeNode* root) {
TreeNode* p=root;
while(p!=nullptr){
if(p->left!=nullptr){
TreeNode *tmp=p->left;
while(tmp!=NULL && tmp->right!=NULL){
tmp=tmp->right;
}
tmp->right=p->right;
p->right=p->left;
p->left=nullptr;
}
p=p->right;
}
}
};