剑指offer刷题记录26——二叉搜索树与双向链表

题目描述

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


public class Solution {
    public TreeNode Convert(TreeNode root) {

        //正常的空值判断
        if(root == null) return null;
        if(root.left == null && root.right == null) return root;

    //1、处理左边的子树
        TreeNode left = Convert(root.left);
        TreeNode p = left;
        while(p != null && p.right != null){
            p = p.right;
        }

        //(1)左子树最后一个结点增加右边指向根结点的指针
        if(left != null){
            p.right = root;
            root.left = p;
        }
    //2、处理右边的子树
        TreeNode right = Convert(root.right);

        //(2)右子树的第一个一个结点增加左边指向根结点的指针
        if(right != null){
            right.left = root;
            root.right = right;
        }

        return left != null ? left : root;       
    }
}

猜你喜欢

转载自blog.csdn.net/qq_37684824/article/details/84141066