美文网首页
114. Flatten Binary Tree to Link

114. Flatten Binary Tree to Link

作者: exialym | 来源:发表于2016-11-16 10:42 被阅读11次

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 Link

      本文链接:https://www.haomeiwen.com/subject/vytrpttx.html