leetcode第114题二叉树展开为链表

123 阅读1分钟

题目: 给你二叉树的根结点 root ,请你将它展开为一个单链表:

  • 展开后的单链表应该同样使用 TreeNode ,其中 right 子指针指向链表中下一个结点,而左子指针始终为 null 。
  • 展开后的单链表应该与二叉树 先序遍历 顺序相同。 题目

我的JavaScript解法

  • 前序遍历的迭代法
/**
 * 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) {
 if (root == null) return ;
 const stack = [];
 stack.push(root);
 let pre = new TreeNode();
 while(stack.length) {
   let curr = stack.pop();
   pre.right = curr;
   pre.left = null;
   if (curr.right !== null)
    stack.push(curr.right);
  if (curr.left !== null)
    stack.push(curr.left);
  pre = curr;
 }
};
  • 前序遍历的递归法
var flatten = function(root) {
  if (root == null) return ;
  const stack = [];
  preorderTraversal(root, stack);
  let pre = stack.shift();
  while(stack.length) {
    let curr = stack.shift();
    pre.left = null;
    pre.right = curr;
    pre = pre.right;
  }
}

const preorderTraversal = (root, stack) => {
  if (root != null) {
    stack.push(root);
    preorderTraversal(root.left, stack);
    preorderTraversal(root.right, stack);
  }
}

解析:

  • 时间复杂度: O(n)O(n)
  • 空间复杂度: O(n)O(n)