题目描述:(链接)
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 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 void flatten(TreeNode* root) { 13 if (root == nullptr) return; 14 15 stack<TreeNode *> cache; 16 cache.push(root); 17 while (!cache.empty()) { 18 auto p = cache.top(); 19 cache.pop(); 20 21 if (p->right) { 22 cache.push(p->right); 23 } 24 25 if (p->left) { 26 cache.push(p->left); 27 } 28 29 p->left = nullptr; 30 if (!cache.empty()) { 31 p->right = cache.top(); 32 } 33 34 } 35 36 } 37 };
[LeetCode]Flatten Binary Tree to Linked List
原文:http://www.cnblogs.com/skycore/p/5021417.html