剑指offer——27. 二叉搜索树与双向链表(Java版)

题目:

剑指offer的题目有挺多都挺典型的,就像这一道。不过书中的代码写的真是ugly,有很多题目LeetCode上都有,可以去LeetCode讨论区看看,经常有一些大神分享,写的代码真是高效、简洁、清晰,剑指offer上的代码不仅变量名定义又长又不知所云,让人看着就很不清晰明了,还有各种没必要的判断让代码看起来非常不直观。

思路:书中已经写的挺清楚了,通过中序遍历来做。

package com.ss.offer;

/**
 * 2018-09-15 下午11:18.
 *
 * @author blank
 */
public class BST2LinkedList {
    public static void main(String[] args) throws Exception {
        BinaryTreeNode root = new BinaryTreeNode(10);
        BinaryTreeNode six = new BinaryTreeNode(6);
        BinaryTreeNode four = new BinaryTreeNode(4);
        BinaryTreeNode eight = new BinaryTreeNode(8);
        BinaryTreeNode fourteen = new BinaryTreeNode(14);
        BinaryTreeNode twelve = new BinaryTreeNode(12);
        BinaryTreeNode sixteen = new BinaryTreeNode(16);
        root.left = six;
        root.right = fourteen;
        six.left = four;
        six.right = eight;
        four.left = null;
        four.right = null;
        eight.left = null;
        eight.right = null;
        fourteen.left = twelve;
        fourteen.right = sixteen;
        twelve.left = null;
        twelve.right = null;
        sixteen.right = null;
        sixteen.left = null;
        BinaryTreeNode res = convert(root);
        while (res != null) {
            System.out.println(res.val);
            res = res.right;
        }
    }

    static BinaryTreeNode convert(BinaryTreeNode root) {

        BinaryTreeNode[] lastNode = new BinaryTreeNode[1];
        convertNode(root, lastNode);
        BinaryTreeNode headNode = lastNode[0];
        while (headNode.left != null)
            headNode = headNode.left;
        return headNode;

    }

    static void convertNode(BinaryTreeNode root, BinaryTreeNode[] last) {
        if (root == null) {
            return;
        }
        convertNode(root.left, last);
        if (last[0] != null) {
            last[0].right = root;
        }
        root.left = last[0];
        last[0] = root;
        convertNode(root.right, last);
    }

    private static class BinaryTreeNode {
        int val;
        BinaryTreeNode left;
        BinaryTreeNode right;

        public BinaryTreeNode(int val) {
            this.val = val;
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/aboutblank/p/9653147.html