1000019. BiNode LCCI
2026/1/12小于 1 分钟约 266 字
1000019. BiNode LCCI
难度: Easy
题目描述
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:
- The number of nodes will not exceed 100000.
解题思路
代码实现
解决方案
java
/**
* 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) {
LinkedList<TreeNode> stack = new LinkedList<>();
TreeNode cur = root;
TreeNode newRoot = null;
TreeNode pre = null;
while (cur != null || !stack.isEmpty()) {
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
cur = stack.pop();
if (newRoot == null) {
newRoot = cur;
pre = cur;
} else {
cur.left = null;
pre.right = cur;
pre = cur;
}
cur = cur.right;
}
return newRoot;
}
}