114. 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

在深度优先搜索这棵树时做点手脚就好了,把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;
    }
    
};

你可能感兴趣的:(114. Flatten Binary Tree to Linked List)