114. Flatten Binary Tree to Linked List(js)

114. Flatten Binary Tree to Linked List

Given a binary tree, flatten it to a linked list in-place.

For example, given the following tree:

    1
   / \
  2   5
 / \   \
3   4   6

The flattened tree should look like:

1
 \
  2
   \
    3
     \
      4
       \
        5
         \
          6
题意:将二叉树拉成链表
代码如下:
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {void} Do not return anything, modify root in-place instead.
 */
var flatten = function(root) {
    if(!root) return ;
    if(root.left) flatten(root.left);
    if(root.right) flatten(root.right);
    let node=root.right;
    root.right=root.left;
    root.left=null;
    while(root.right) root=root.right;
    root.right=node;
};

 

posted @ 2019-04-21 22:06  mingL  阅读(120)  评论(0编辑  收藏  举报