剑指offer第2版36题:二叉搜索树与双向链表

小渣渣的算法学习笔记:2018秋招备战


数据结构类算法总结:二叉树 链表


1.题目描述:

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

2.代码实现:

public class Solution36 {
    private static class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;
        public TreeNode(int val) {
            this.val = val;
        }
    }
    public static void main(String[] args) {
        Solution36 s = new Solution36();
        TreeNode t1 = new TreeNode(10);
        TreeNode t2 = new TreeNode(6);
        TreeNode t3 = new TreeNode(14);
        TreeNode t4 = new TreeNode(4);
        TreeNode t5 = new TreeNode(8);
        TreeNode t6 = new TreeNode(12);
        TreeNode t7 = new TreeNode(16);

        t1.left = t2;
        t1.right = t3;
        t2.left = t4;
        t2.right = t5;
        t3.left = t6;
        t3.right = t7;

        TreeNode t = s.convert(t1);
//        System.out.println(t.val);
        while(t!= null){
            System.out.print(t.val+" ");
            t = t.left;
        }
    }

    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;
        // 2.定位至左子树双链表最后一个节点
        while(p!=null&&p.right!=null){
            p = p.right;
        }
        // 3.如果左子树链表不为空的话,将当前root追加到左子树链表
        if(left!=null){
            p.right = root;
            root.left = p;
        }
        // 4.将右子树构造成双链表,并返回链表头节点
        TreeNode right = convert(root.right);
        // 5.如果右子树链表不为空的话,将该链表追加到root节点之后
        if(right!=null){
            right.left = root;
            root.right = right;
        }
        return left!=null?left:root;
    }

    /*
    public TreeNode convert(TreeNode root){
        TreeNode lastNodeInList = null;
        convertNode(root,lastNodeInList);
        //lastNodeInList指向双向链表的尾结点
        //我们需要返回头结点
        TreeNode headOfList = lastNodeInList;
        while(headOfList != null && headOfList.left != null)
            headOfList = headOfList.left;
        return headOfList;
    }
    //把左子树中最大的节点、根结点、右子树中最小的结点链接起来
    public void convertNode(TreeNode pnode,TreeNode lastNodeInList){
        if(pnode == null) return;
        TreeNode pcurrent = pnode;
        if(pcurrent.left!= null){
            convertNode(pcurrent.left,lastNodeInList);
        }
        pcurrent.left = lastNodeInList;
        if(lastNodeInList != null){
            lastNodeInList.right = pcurrent;
        }
        lastNodeInList = pcurrent;
        if(pcurrent.right != null){
            convertNode(pcurrent.right,lastNodeInList);
        }
    }
    */
}

你可能感兴趣的:(剑指Offer代码整理)