Flatten Binary Tree to Linked List [LeetCode]
2013-11-27 15:15
218 查看
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
The flattened tree should look like:
click to show hints.
Hints:
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
Solution:
For example,
Given
1 / \ 2 5 / \ \ 3 4 6
The flattened tree should look like:
1 \ 2 \ 3 \ 4 \ 5 \ 6
click to show hints.
Hints:
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
Solution:
void flatten(TreeNode *root) { stack<TreeNode *> nodes; if(root == NULL) return; nodes.push(root); TreeNode * pre = root; while(nodes.size() != 0){ TreeNode * node = nodes.top(); nodes.pop(); if(node->right != NULL) nodes.push( node->right); if(node->left != NULL) nodes.push( node->left); pre->left = NULL; if(node != root){ pre->right = node; pre = pre->right; } } }
相关文章推荐
- leetcode 114: 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]114 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)
- Flatten Binary Tree to Linked List ---LeetCode
- leetcode_question_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 刷题之路 69 Flatten Binary Tree to Linked List