We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Difficulty: 中等
Related Topics: 栈, 树, 深度优先搜索, 链表, 二叉树
给你二叉树的根结点 root ,请你将它展开为一个单链表:
root
TreeNode
right
null
示例 1:
输入:root = [1,2,5,3,4,null,6] 输出:[1,null,2,null,3,null,4,null,5,null,6]
示例 2:
输入:root = [] 输出:[]
示例 3:
输入:root = [0] 输出:[0]
提示:
[0, 2000]
-100 <= Node.val <= 100
**进阶:**你可以使用原地算法(O(1) 额外空间)展开这棵树吗?
O(1)
Language: JavaScript
/** * 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. */ // 1. 先用两个变量把原先的左右子树保持起来 // 2. 将左子树作为右子树 // 3. 将原先的右子树接到当前右子树的末端 // 递归 var flatten = function(root) { // 递归终止 if (root === null) return // 分别递归左右节点 const left = root.left const right = root.right flatten(left) flatten(right) // 将树的right节点替换为left节点 root.right = root.left root.left = null // 循环 找到最右的节点 while (root.right) root = root.right // 最右的节点 指向right节点 root.right = right }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
114. 二叉树展开为链表
Description
Difficulty: 中等
Related Topics: 栈, 树, 深度优先搜索, 链表, 二叉树
给你二叉树的根结点
root
,请你将它展开为一个单链表:TreeNode
,其中right
子指针指向链表中下一个结点,而左子指针始终为null
。示例 1:
示例 2:
示例 3:
提示:
[0, 2000]
内-100 <= Node.val <= 100
**进阶:**你可以使用原地算法(
O(1)
额外空间)展开这棵树吗?Solution
Language: JavaScript
The text was updated successfully, but these errors were encountered: