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
void flatten(TreeNode *root) { //C++ if(root == NULL) return; stack<TreeNode* > myStack; queue<TreeNode* > myQueue; TreeNode *p = root; while(p!=NULL || !myStack.empty()) { while(p!=NULL){ myQueue.push(p); myStack.push(p); p=p->left; } p = myStack.top(); myStack.pop(); p = p->right; } p = myQueue.front(); myQueue.pop(); while(!myQueue.empty()){ TreeNode* temp = myQueue.front(); p->right = temp; p->left = NULL; p = temp; myQueue.pop(); } }
[leetcode]Flatten Binary Tree to Linked List
原文地址:http://blog.csdn.net/chenlei0630/article/details/42718277