Open wengzc opened 4 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) {
while (root) {
if (!root.left) {
root = root.right
} else {
let p = root.left
while (p.right) {
p = p.right
}
p.right = root.right
root.right = root.left
root.left = null
root = root.right
}
}
};
解法二:递归法
var flatten = function (root) {
if (!root) {
return
}
flatten(root.left)
flatten(root.right)
let tmep = root.right
root.right = root.left
root.left = null
while (root.right) {
root = root.right
}
root.right = tmep
};
给定一个二叉树,原地将它展开为一个单链表。
例如,给定二叉树
题目链接:https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list