wengzc / leetcode

Record the leetcode
1 stars 0 forks source link

114. 二叉树展开为链表 #162

Open wengzc opened 4 years ago

wengzc commented 4 years ago

给定一个二叉树,原地将它展开为一个单链表。

 

例如,给定二叉树

  1
   / \
  2   5
 / \   \
3   4   6
将其展开为:

1
 \
  2
   \
    3
     \
      4
       \
        5
         \
          6

题目链接:https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list

wengzc commented 4 years ago

解法一:迭代法

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {void} Do not return anything, modify root in-place instead.
 */
var flatten = function (root) {
  while (root) {
    if (!root.left) {
      root = root.right
    } else {
      let p = root.left
      while (p.right) {
        p = p.right
      }
      p.right = root.right
      root.right = root.left
      root.left = null
      root = root.right
    }
  }
};

解法二:递归法

var flatten = function (root) {
    if (!root) {
        return
    }
    flatten(root.left)
    flatten(root.right)
    let tmep = root.right
    root.right = root.left
    root.left = null
    while (root.right) {
        root = root.right
    }
    root.right = tmep
};