Open Tcdian opened 3 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) {
if (root === null) {
return;
}
flatten(root.left);
flatten(root.right);
const next = root.right;
root.right = root.left;
root.left = null;
while (root.right !== null) {
root = root.right;
}
root.right = next;
};
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
/**
Do not return anything, modify root in-place instead.
*/
function flatten(root: TreeNode | null): void {
if (root === null) {
return;
}
flatten(root.left);
flatten(root.right);
const next = root.right;
root.right = root.left;
root.left = null;
while (root.right !== null) {
root = root.right;
}
root.right = next;
};
/**
* 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) {
let current = root;
while(current !== null) {
if (current.left !== null) {
const next = current.left;
let patrol = next;
while(patrol.right !== null) {
patrol = patrol.right;
}
patrol.right = current.right;
current.right = next;
current.left = null;
}
current = current.right;
}
};
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
/**
Do not return anything, modify root in-place instead.
*/
function flatten(root: TreeNode | null): void {
if (root === null) {
return;
}
flatten(root.left);
flatten(root.right);
let patrol = root.left;
if (patrol !== null) {
const next = root.right;
root.right = patrol;
while(patrol.right !== null) {
patrol = patrol.right;
}
patrol.right = next;
root.left = null;
}
};
114. Flatten Binary Tree to Linked List
给定一个二叉树,原地将它展开为链表。
例如,给定二叉树
将其展开为: