1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| class TreeNode{ int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val){ this.val = val; } }
public class BSTToLinkedList{ public TreeNode convert(TreeNode root){ if(root == null){ return null; } TreeNode head = new TreeNode(0); TreeNode prev = new TreeNode(0); convertHelper(TreeNode root, TreeNode head, TreeNode prev); return head.left; } private void convertHelper(TreeNode root, TreeNode head, TreeNode prev){ if(root == null){ return; } convertHelper(root.left, head, prev); if(head.left == null){ head.left = root; } if(prev.left == null){ prev.left = root; }else{ prev.left.right = root; root.left = prev.left; prev.left = root; } convertHelper(root.right, head, prev); } }
|