剑指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;
        }
    }
}

 

 

 

转载于:https://www.cnblogs.com/aboutblank/p/9653147.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值