问题描述:
Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1 / 2 5 / 3 4 6
The flattened tree should look like:
1 2 3 4 5 6
解题思路:
因为要把所有的节点都放在右节点上。
我们可以用栈存储当前遇到的右节点,并将左节点放到右节点上并将左节点设为空(一开始我忘了。。TAT)!
当当前节点cur为空时,我们从栈中弹出一个节点并将其连接到上一个节点pre的右边。
代码:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void flatten(TreeNode* root) { if(!root) return; stack<TreeNode*> stk; TreeNode *cur = root; TreeNode *pre = root; while(cur || !stk.empty()){ if(cur){ if(cur->right) stk.push(cur->right); cur->right = cur->left; cur->left = NULL; pre = cur; cur = cur->right; }else{ cur = stk.top(); pre->right = cur; stk.pop(); } } } };