1. 程式人生 > >演算法題(十九):二叉搜尋樹轉雙鏈表

演算法題(十九):二叉搜尋樹轉雙鏈表

題目描述

輸入一棵二叉搜尋樹,將該二叉搜尋樹轉換成一個排序的雙向連結串列。要求不能建立任何新的結點,只能調整樹中結點指標的指向。

輸入輸出示例:

{10,6,4,8,14,12,16}

from left to right:4,6,8,10,12,14,16 from right to left:16,14,12,10,8,6,4

{1,2,3,4,5}

from left to right:1,2,3,4,5 from right to left:5,4,3,2,1

{1}

from left to right:1 from right to left:1


分析

方法一:可用二叉樹中序遍歷方法來遍歷BST,遍歷過程中,轉接結點的左右結點。示例解析圖如下。

方法二:用遞迴法來求解。把左子樹排成雙向連結串列後,返回第一個結點,再把root結點接到左表後面,把右子樹也排成雙向連結串列並返回第一個結點,把右表接到root結點後面。


程式碼一

import java.util.Stack;

public class BST2List {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TreeNode root = new TreeNode(10);
		root.left = new TreeNode(6);
		root.left.left = new TreeNode(4);
		root.left.right = new TreeNode(8);
		root.right = new TreeNode(14);
		root.right.left = new TreeNode(12);
		root.right.right = new TreeNode(16);
		root = convert(root);
		while(root != null){
			System.out.println(root.value);
			root = root.right;
		}
	}
	
	public static TreeNode convert(TreeNode root){
		Stack<TreeNode> stack = new Stack<>();
		if(root == null){
			return null;
		}
		stack.push(root);
		TreeNode sNode = root;
		while(sNode.left != null){
			stack.push(sNode.left);
			sNode = sNode.left;
		}
		TreeNode node1 = stack.pop();
		root = node1;
		if(stack.isEmpty() && root.right!=null){
			stack.push(root.right);
		}
		while(!stack.isEmpty()){
			
				TreeNode node2 = stack.pop();
				node1.right = node2;
				node2.left = node1;
				node1 = node2;
				TreeNode tempNode = node2.right;
				if(tempNode != null){
					stack.push(tempNode);
					while(tempNode.left != null){
						stack.push(tempNode.left);
						tempNode = tempNode.left;
					}
				}
			
		}
		return root;
	}

}

程式碼二

public class BST2List2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TreeNode root = new TreeNode(10);
		root.left = new TreeNode(6);
		root.left.left = new TreeNode(4);
		root.left.right = new TreeNode(8);
		root.right = new TreeNode(14);
		root.right.left = new TreeNode(12);
		root.right.right = new TreeNode(16);
		root = convert(root);
		while(root != null){
			System.out.println(root.value);
			root = root.right;
		}
	}
	
	public static TreeNode convert(TreeNode root){
		if(root == null){
			return null;
		}
		if(root.left==null && root.right==null){
			return root;
		}
		TreeNode left = convert(root.left);
		TreeNode p = left;
		while(p!=null && p.right != null){
			p=p.right;
		}
		if(left != null){
			p.right=root;
			root.left=p;
		}
		TreeNode right = convert(root.right);
		if(right != null){
			right.left = root;
			root.right = right;
		}
		return left != null ? left : root;
		
	}

}