Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
1 class Solution { 2 public: 3 queue<TreeNode*> Q; 4 5 void preorder(TreeNode *root) 6 { 7 if(root) 8 { 9 Q.push(root); 10 preorder(root->left); 11 preorder(root->right); 12 } 13 14 } 15 16 void flat(TreeNode * root) 17 { 18 19 if(!Q.empty()) 20 { 21 root->right=Q.front(); 22 root->left=NULL; 23 Q.pop(); 24 flat(root->right); 25 } 26 27 28 } 29 30 void flatten(TreeNode* root) { 31 if(root==NULL) return ; 32 preorder(root); 33 root=Q.front(); 34 Q.pop(); 35 root->left=NULL; 36 flat(root); 37 38 } 39 };
【leetcode】Flatten Binary Tree to Linked List
原文:http://www.cnblogs.com/jawiezhu/p/4496312.html