同步操作将从 doocs/leetcode 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
The data structure TreeNode
is used for binary tree, but it can also used to represent a single linked list (where left is null, and right is the next node in the list). Implement a method to convert a binary search tree (implemented with TreeNode
) into a single linked list. The values should be kept in order and the operation should be performed in place (that is, on the original data structure).
Return the head node of the linked list after converting.
Note: This problem is slightly different from the original one in the book.
Example:
Input: [4,2,5,1,3,null,6,0] Output: [0,null,1,null,2,null,3,null,4,null,5,null,6]
Note:
See 897. Increasing Order Search Tree.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def convertBiNode(self, root: TreeNode) -> TreeNode:
if root is None:
return None
left = self.convertBiNode(root.left)
right = self.convertBiNode(root.right)
if left is None:
root.right = right
return root
res = left
while left and left.right:
left = left.right
left.right = root
root.right = right
root.left = None
return res
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode convertBiNode(TreeNode root) {
if (root == null) return null;
TreeNode left = convertBiNode(root.left);
TreeNode right = convertBiNode(root.right);
if (left == null) {
root.right = right;
return root;
}
TreeNode res = left;
while (left != null && left.right != null) {
left = left.right;
}
left.right = root;
root.right = right;
root.left = null;
return res;
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。