剑指offer45

209 阅读1分钟

题目描述

输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。

解题思路分析

这道跟着下面的代码,使用递归就可以看懂了

代码实现

public TreeNode convert(TreeNode root) {
    if(root == null) {
        return null;
    }
    if (root.left == null && root.right == null) {
        return root;
    }
    //递归转换好左子树
    TreeNode left = convert(root.left);
    TreeNode temp = left;
    //找到左子树转换成链表之后的最后一个节点
    while (temp != null && temp.right != null) {
        temp = temp.right;
    }
    //找到最后一个节点之后就开始将root连接到其后面
    if (temp != null) {
        temp.right = root;
        root.left = temp;
    }
    //递归实现将右子树转换成链表
    TreeNode right = covert(root.right);
    if (right != null) {
        root.right = right;
        right.left = root;
    }
    //返回链表头
    return left == null ? root : left;
}