![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/0d537ce95f3fbb6fa8f626f6624229a7.png)
排序二叉树用中序遍历,先来个中序遍历的模板
public class Solution {
public TreeNode Convert(TreeNode pRootOfTree) {
if(pRootOfTree == null) {
return null;
}
Convert(pRootOfTree.left);
(这里写对应的操作)
Convert(pRootOfTree.right);
}
}
我们需要拿到当前节点的前一个节点,所以再递归的时候用一个变量pre保存前一个节点
public class Solution {
TreeNode pre = null;
public TreeNode Convert(TreeNode pRootOfTree) {
if(pRootOfTree == null) {
return null;
}
Convert(pRootOfTree.left);
if(pre != null) {
pre.right = pRootOfTree;
pRootOfTree.left = pre;
}
pre = pRootOfTree;
Convert(pRootOfTree.right);
return pre ;
}
}
但是返回的pre是链表的尾节点,再创建一个临时节点保存头节点
public class Solution {
TreeNode root = null;
TreeNode pre = null;
public TreeNode Convert(TreeNode pRootOfTree) {
if(pRootOfTree == null) {
return null;
}
Convert(pRootOfTree.left);
if(root == null) {
root = pRootOfTree;
}
if(pre != null) {
pre.right = pRootOfTree;
pRootOfTree.left = pre;
}
pre = pRootOfTree;
Convert(pRootOfTree.right);
return root;
}
}