标签:
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
If you notice carefully in the flattened tree, each node‘s right child points to the next node of a pre-order traversal.
1 void flatten(TreeNode *root) 2 { 3 vector<TreeNode *> tree_nodes; 4 stack<TreeNode *> stree; 5 TreeNode *visit = root; 6 if (root == NULL) 7 return; 8 while (!stree.empty() && visit != NULL) 9 { 10 if (visit != NULL) 11 { 12 tree_nodes.push_back(visit); 13 if (visit->right != NULL) 14 stree.push(visit); 15 visit = visit->left; 16 } 17 else 18 { 19 visit = stree.top(); 20 stree.pop(); 21 } 22 } 23 24 visit = root; 25 visit->left = NULL; 26 for (int i = 1; i < tree_nodes.size(); i++) 27 { 28 visit->right = tree_nodes[i]; 29 visit->left = NULL; 30 visit = visit->right; 31 } 32 }
leetcode 114 . Flatten Binary Tree to Linked List
标签:
原文地址:http://www.cnblogs.com/ym65536/p/4286619.html