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
在深度優先搜索這棵樹時做點手腳就好了,把pop出來的元素的右節點指向棧頂元素,左節點指空。
var flatten = function(root) {
if (!root)
return;
var stack = [root];
var last;
while (stack.length!==0) {
last = stack.pop();
if (last.right)
stack.push(last.right);
if (last.left)
stack.push(last.left);
last.right = stack[stack.length-1];
last.left = null;
}
};