Domanda di colloquio di Yahoo

How to convert a binary search tree into an ordered doubly linked list?

Risposta di colloquio

Anonimo

25 ott 2016

Consider the left pointer equivalent to the prev pointer, and the right pointer equivalent to the next pointer in a linked list. Recursively link the rightmost node of the left subtree to the root, and link the root to the leftmost node of the right subtree. public static TreeNode[] BSTtoDLL (TreeNode root) { if(root == null || root.isLeaf()) return null; TreeNode[] prev = BSTtoDLL(root.left); TreeNode[] next = BSTtoDLL(root.right); if(prev != null) { prev[1].right = root; root.left = prev[1]; } if(next != null) { next[0].left = root; root.right = next[0]; } return new TreeNode[] {prev[0], next[1]}; }