采用中序遍历来做。需要注意的是牛客网不需要我们把头和尾相连接。代码如下:
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
TreeNode head, prev;
public TreeNode Convert(TreeNode pRootOfTree) {
if(pRootOfTree == null){
return pRootOfTree;
}
helper(pRootOfTree);
return head;
}
private void helper(TreeNode curr){
if(curr == null){
return;
}
helper(curr.left);
if(prev == null){
head = curr;
}else{
prev.right = curr;
}
curr.left = prev;
prev = curr;
helper(curr.right);
}
}