Flatten Binary Tree to Linked List
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1 / \ 2 5 / \ \ 3 4 6The flattened tree should look like:
1 \ 2 \ 3 \ 4 \ 5 \ 6
Hints:
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
解题思路:非递归前序遍历的应用改进,左右不空时压右
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void treeToLine(TreeNode *root, stack<TreeNode*> &stn){
if(root->left == NULL && root->right == NULL){
if(stn.empty()) return;
root->right = stn.top(); //栈中还有结点时出栈
stn.pop();
}else if(root->left && root->right == NULL){
root->right = root->left;
}else if(root->left && root->right){
stn.push(root->right); //左右都不空时,右子树进栈
root->right = root->left;
}
root->left = NULL;
treeToLine(root->right, stn);
}
void flatten(TreeNode *root) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(NULL == root) return;
stack<TreeNode*> stn;
treeToLine(root, stn);
}
};