[leetcode]Flatten Binary Tree to Linked List
2014-04-20 20:05
453 查看
Flatten Binary Tree to Linked List
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
Hints:
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
解题思路:非递归前序遍历的应用改进,左右不空时压右
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void treeToLine(TreeNode *root, stack<TreeNode*> &stn){ if(root->left == NULL && root->right == NULL){ if(stn.empty()) return; root->right = stn.top(); //栈中还有结点时出栈 stn.pop(); }else if(root->left && root->right == NULL){ root->right = root->left; }else if(root->left && root->right){ stn.push(root->right); //左右都不空时,右子树进栈 root->right = root->left; } root->left = NULL; treeToLine(root->right, stn); } void flatten(TreeNode *root) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. if(NULL == root) return; stack<TreeNode*> stn; treeToLine(root, stn); } };
相关文章推荐
- LeetCode - Flatten Binary Tree to Linked List
- LeetCode: Flatten Binary Tree to Linked List
- LeetCode Flatten Binary Tree to Linked List
- LeetCode114 Flatten Binary Tree to Linked List
- [LeetCode] Flatten Binary Tree to Linked List
- Leetcode-Flatten Binary Tree to Linked List
- LeetCode_Flatten Binary Tree to Linked List
- [LeetCode 114] Flatten Binary Tree to Linked List
- [Leetcode]Flatten Binary Tree to Linked List
- LeetCode:Flatten Binary Tree to Linked List
- LeetCode (Flatten Binary Tree to Linked List)
- leetcode - Flatten Binary Tree to Linked List
- Leetcode---Flatten Binary Tree to Linked List
- LeetCode--Flatten Binary Tree to Linked List
- [leetcode] Flatten Binary Tree to Linked List
- [leetcode] Flatten Binary Tree to Linked List
- LeetCode[Tree]: Flatten Binary Tree to Linked List
- 【leetcode】Flatten Binary Tree to Linked List
- [面试真题] LeetCode:Flatten Binary Tree to Linked List
- 【LeetCode-面试算法经典-Java实现】【114-Flatten Binary Tree to Linked List(二叉树转单链表)】