剑指offer-二叉搜索树与双向链表

 

/*输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
*/
class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}

public class Solution {
    private TreeNode pre = null;
    private TreeNode head = null;
    public TreeNode Convert(TreeNode pRootOfTree) {
        inOrder(pRootOfTree);
        return head;
    }
    public void inOrder(TreeNode node) {
        if(node == null) return ;
        inOrder(node.left);
        node.left = pre;//当前结点指向左指针指向前驱结点
        if(pre != null) {
            pre.right = node;//前驱结点右指针指向当前结点
        }
        pre = node;//前驱 = 当前
        if(head == null) head = node;
        inOrder(node.right);//遍历右子树
    }
}

 

posted @ 2019-02-01 01:34  Roni_i  阅读(98)  评论(0编辑  收藏  举报