Convert a BST to a sorted doubly-linked list in-place

Convert a BST to a sorted doubly-linked list in-place


after conversion: 1 = 3 = 4 = 6 = 7 = 8 = 10 = 13 = 14


public class Solution {
	static Node lastNode = null;
	
	public static void main(String[] args) {
		Node n1 = new Node(7);
		Node n2 = new Node(3);
		Node n3 = new Node(10);
		Node n4 = new Node(8);
		Node n5 = new Node(20);
		
		n1.left = n2;
		n1.right = n3;
		n3.left = n4;
		n3.right = n5;
		
		Node head = BSTtoList(n1);
		while(head != null) {
			System.out.println(head.value);
			head = head.right;
		}
	}
	
	public static Node BSTtoList(Node root) {
		convert(root);
		while (lastNode.left != null) {
			lastNode = lastNode.left;
		}
		return lastNode;
	}
	
	public static void convert(Node current) {
		if (current == null) return;
		if (current.left != null)
			convert(current.left);
		current.left = lastNode;
		if (lastNode != null) {
			lastNode.right = current;
		}
		lastNode = current;	
		if (current.right != null)
			convert(current.right);
	}
}

class Node {
	Node left;
	Node right;
	
	int value;
	
	Node(int v) {
		value = v;
	}
}
blog.csdn.net/beiyetengqing

你可能感兴趣的:(Convert a BST to a sorted doubly-linked list in-place)