題目:this
劍指offer的題目有挺多都挺典型的,就像這一道。不過書中的代碼寫的真是ugly,有不少題目LeetCode上都有,能夠去LeetCode討論區看看,常常有一些大神分享,寫的代碼真是高效、簡潔、清晰,劍指offer上的代碼不只變量名定義又長又不知所云,讓人看着就很不清晰明瞭,還有各類不必的判斷讓代碼看起來很是不直觀。spa
思路:書中已經寫的挺清楚了,經過中序遍從來作。code
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; } } }