码迷,mamicode.com
首页 > 其他好文 > 详细

Solution 1: BST转双向链表

时间:2015-06-28 18:46:17      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:

问题描述

将一棵二叉查找树(BST)转为有序的双向链表。

例如,有一颗BST如下:

2

|  \

1    3

转成双向链表为:

1=2=3

 

解决思路


1. 保持有序:中序遍历;

2. 双向链表:记录链表的头节点,遍历过程中记录前一个节点并且保持双向连接关系。

 

程序

class TreeNode {
	public int val;
	public TreeNode left;
	public TreeNode right;

	public TreeNode(int _val) {
		val = _val;
	}
}

class BSTToDoublyLinkedList {
	public TreeNode convertToDoublyLinkedList(TreeNode root) {
		if (root == null) {
			return null;
		}

		TreeNode head = new TreeNode(0);
		TreeNode pre = new TreeNode(0);
		convertHelper(root, head, pre);
		return head.left;
	}

	private void convertHelper(TreeNode root, TreeNode head, TreeNode pre) {
		if (root == null) {
			return;
		}
		convertHelper(root.left, head, pre);
		if (head.left == null) {
			head.left = root; // record the head
		} 
		if (pre.left == null) {
			pre.left = root;
		} else {
			pre.left.right = root;
			root.left = pre.left;
			pre.left = root; // to next
		}
		convertHelper(root.right, head, pre);
	}
}

  

附加测试程序:

public class ConvertTest {
	public static void main(String[] args) {
		TreeNode n2 = new TreeNode(3);
		n2.left = new TreeNode(1);
		n2.left.right = new TreeNode(2);

		BSTToDoublyLinkedList toDoublyLinkedList = new BSTToDoublyLinkedList();
		TreeNode head = toDoublyLinkedList.convertToDoublyLinkedList(n2);
		printDoublyLinkedList(head);
	}

	private static void printDoublyLinkedList(TreeNode head) {
		TreeNode node = head;
		TreeNode last = null;

		System.out.println("left --> right");
		while (node != null) {
			System.out.print(node.val + " ");
			if (node.right == null) {
				last = node;
			}
			node = node.right;
		}
		
		System.out.println();
		System.out.println("right --> left");

		while (last != null) {
			System.out.print(last.val + " ");
			last = last.left;
		}
	}
}

 

时间/空间复杂度

时间复杂度:中序遍历的时间复杂度,O(n);

空间复杂度:O(h),递归栈。

 

Solution 1: BST转双向链表

标签:

原文地址:http://www.cnblogs.com/harrygogo/p/4605841.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!