The question and solution are from: http://www.geeksforgeeks.org/convert-given-binary-tree-doubly-linked-list-set-3/
Given a Binary Tree (BT), convert it to a Doubly Linked List(DLL) In-Place. The left and right pointers in nodes are to be used as previous and next pointers respectively in converted DLL. The order of nodes in DLL must be same as Inorder of the given Binary Tree. The first node of Inorder traversal (left most node in BT) must be head node of the DLL.
曾经的我能够想到的方法就是利用LinkedList来保存每个node,然后修改每个node的left和right。
下面这个方法现在想起来好像并不那么复杂了, 值得学习一下。
1 public class BinaryTree 2 { 3 Node root, head; 4 5 // Initialize previously visited node as NULL. This is 6 // static so that the same value is accessible in all recursive 7 // calls 8 Node prev = null; 9 10 // A simple recursive function to convert a given Binary tree 11 // to Doubly Linked List 12 // root --> Root of Binary Tree 13 void BinaryTree2DoubleLinkedList(Node root) { 14 // Base case 15 if (root == null) return; 16 17 // Recursively convert left subtree 18 BinaryTree2DoubleLinkedList(root.left); 19 20 // Now convert this node 21 if (prev == null){ 22 head = root; 23 } else { 24 root.left = prev; 25 prev.right = root; 26 } 27 prev = root; 28 29 // Finally convert right subtree 30 BinaryTree2DoubleLinkedList(root.right); 31 } 32 33 void printList(Node node) 34 { 35 while (node != null) 36 { 37 System.out.print(node.data + " "); 38 node = node.right; 39 } 40 } 41 42 // Driver program to test above functions 43 public static void main(String[] args) 44 { 45 // Let us create the tree as shown in above diagram 46 BinaryTree tree = new BinaryTree(); 47 tree.root = new Node(10); 48 tree.root.left = new Node(12); 49 tree.root.right = new Node(15); 50 tree.root.left.left = new Node(25); 51 tree.root.left.right = new Node(30); 52 tree.root.right.left = new Node(36); 53 54 // convert to DLL 55 tree.BinaryTree2DoubleLinkedList(tree.root); 56 57 // Print the converted List 58 tree.printList(tree.head); 59 60 } 61 } 62 63 64 class Node 65 { 66 int data; 67 Node left, right; 68 69 public Node(int data) 70 { 71 this.data = data; 72 left = right = null; 73 } 74 }
时间: 2024-10-16 06:30:08