sweet1cris

Untitled

Feb 5th, 2018
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.82 KB | None | 0 0
  1.  
  2. /**
  3.  * Definition of TreeNode:
  4.  * public class TreeNode {
  5.  *     public int val;
  6.  *     public TreeNode left, right;
  7.  *     public TreeNode(int val) {
  8.  *         this.val = val;
  9.  *         this.left = this.right = null;
  10.  *     }
  11.  * }
  12.  * Definition for Doubly-ListNode.
  13.  * public class DoublyListNode {
  14.  *     int val;
  15.  *     DoublyListNode next, prev;
  16.  *     DoublyListNode(int val) {
  17.  *         this.val = val;
  18.  *         this.next = this.prev = null;
  19.  *     }
  20.  * }
  21.  */
  22.  
  23. class ResultType {
  24.     DoublyListNode first, last;
  25.    
  26.     public ResultType(DoublyListNode first, DoublyListNode last) {
  27.         this.first = first;
  28.         this.last = last;
  29.     }
  30. }
  31.  
  32. public class Solution {
  33.     /**
  34.      * @param root: The root of tree
  35.      * @return: the head of doubly list node
  36.      */
  37.     public DoublyListNode bstToDoublyList(TreeNode root) {  
  38.         if (root == null) {
  39.             return null;
  40.         }
  41.        
  42.         ResultType result = helper(root);
  43.         return result.first;
  44.     }
  45.    
  46.     public ResultType helper(TreeNode root) {  
  47.         if (root == null) {
  48.             return null;
  49.         }
  50.        
  51.         ResultType left = helper(root.left);
  52.         ResultType right = helper(root.right);
  53.         DoublyListNode node = new DoublyListNode(root.val);
  54.        
  55.         ResultType result = new ResultType(null, null);
  56.        
  57.         if (left == null) {
  58.             result.first = node;
  59.         } else {
  60.             result.first = left.first;
  61.             left.last.next = node;
  62.             node.prev = left.last;
  63.         }
  64.        
  65.         if (right == null) {
  66.             result.last = node;
  67.         } else {
  68.             result.last = right.last;
  69.             right.first.prev = node;
  70.             node.next = right.first;
  71.         }
  72.        
  73.         return result;
  74.     }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment