Skip to main content

114. Flatten Binary Tree to Linked List

分析

每个节点要处理的问题是一样的

在根结点思考整体操作 -> 递归和操作代码的相对位置
在靠近叶子结点(Option)思考操作代码

Pasted image 20220429080057.png

题解

/**
* 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) {
return
}
flatten(root.left)
flatten(root.right)
const left = root.left, right = root.right
root.left = null
root.right = left
let p = root
while (p.right) {
p = p.right
}
p.right = right
};