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 法I:堆栈
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; TreeNode* flatRoot = new TreeNode(root->val); TreeNode* flatNode = flatRoot; TreeNode* current; stack<TreeNode*> tree_stack; //栈是先入后出,所以反序放入栈,即先右儿子,再左儿子 if(root->right) { tree_stack.push(root->right); } if(root->left) { tree_stack.push(root->left); } while(!tree_stack.empty()) { current = tree_stack.top(); tree_stack.pop(); flatNode->right = new TreeNode(current->val); flatNode = flatNode->right; //将出栈元素视为根节点,再次将它的右儿子、左儿子放入栈 if(current->right) { tree_stack.push(current->right); } if(current->left) { tree_stack.push(current->left); } } *root = *flatRoot; } };
法II:递归,前序遍历
class Solution { public: void flatten(TreeNode *root) { if(!root) return; TreeNode* newRoot = new TreeNode(root->val); preOrderTraverse(root, newRoot); *root = *newRoot; } TreeNode* preOrderTraverse(TreeNode *root, TreeNode * newRoot) { if(root->left) { newRoot->right = new TreeNode(root->left->val); newRoot = preOrderTraverse(root->left, newRoot->right); } if(root->right) { newRoot->right = new TreeNode(root->right->val); newRoot = preOrderTraverse(root->right, newRoot->right); } return newRoot; } };
时间: 2024-12-19 20:30:16