Skip to content

114. Flatten Binary Tree to Linked List

https://leetcode.com/problems/flatten-binary-tree-to-linked-list/

js
/**
 * 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.
 */
function flatten(root) {
  if (!root) {
    return
  }

  flatten(root.left)
  flatten(root.right)

  if (root.left) {
    let current = root.left
    while (current.right) {
      current = current.right
    }
    current.right = root.right
    root.right = root.left
    root.left = null
  }
}
py
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None


class Solution(object):

    def flatten(self, root):
        """
        :type root: TreeNode
        :rtype: void Do not return anything, modify root in-place instead.
        """
        if root is None:
            return

        self.flatten(root.left)
        self.flatten(root.right)

        if root.left:
            current = root.left
            while current.right:
                current = current.right
            current.right = root.right
            root.right = root.left
            root.left = None
go
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func flatten(root *TreeNode) {
	if root == nil {
		return
	}

	flatten(root.Left)
	flatten(root.Right)

	if root.Left != nil {
		current := root.Left
		for current.Right != nil {
			current = current.Right
		}
		current.Right = root.Right
		root.Right = root.Left
		root.Left = nil
	}
}