LeetCode: Flatten Binary Tree To Linked List Solution

1/**
2 * Definition for a binary tree node.
3 * function TreeNode(val, left, right) {
4 * this.val = (val===undefined ? 0 : val)
5 * this.left = (left===undefined ? null : left)
6 * this.right = (right===undefined ? null : right)
7 * }
8 */
9/**
10 * @param {TreeNode} root
11 * @return {void} Do not return anything, modify root in-place instead.
12 */
13var flatten = function (root) {
14 let iter = root
15 while (iter) {
16 if (iter.left) {
17 let last = iter.left
18 while (last.right) last = last.right
19 last.right = iter.right
20 iter.right = iter.left
21 iter.left = null
22 }
23 iter = iter.right
24 }
25}

Comments

Loading comments...

Tags

leetcode

tree

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Valid Number

HoningJS

Search Posts