先上代码
class Solution {
TreeNode head = new TreeNode(0);
TreeNode t = head;
public TreeNode convertBiNode(TreeNode root) {
if(root == null)
return root;
convertBiNode(root.left);
t.right = root;
root.left = null;
t = root;
convertBiNode(root.right);
return head.right;
}
}
想得通就很简单,想不通的就会把自己绕进去,往往想不通的就是想太多了
首先我们知道对一棵搜索树中序遍历的结果就是题目所需要的有序链表,所以问题就来到了如何生成链表
考验对中序遍历的理解,需要知道在递归函数中两个自调用之间的代码是严格按照顺序来的,即
...
t.right = root;
root.left = null;
t = root;
...
这段代码第一次运行时对应的root就是链表的开头,第二次运行就是链表的第二节,所以只要定义一个指针依次把每个节点连上去即可
同时为了方便返回头结点的指针,所以先定义一个虚节点作为头结点。