码迷,mamicode.com
首页 > 其他好文 > 详细

426. Convert Binary Search Tree to Sorted Doubly Linked List

时间:2018-08-09 18:29:05      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:stack   code   nod   amp   arch   document   arc   ||   root   

426. Convert Binary Search Tree to Sorted Doubly Linked List


https://www.youtube.com/watch?v=FsxTX7-yhOw&t=1210s



https://docs.google.com/document/d/1IIn5rXrUumqpxRrMKo76FbBx1ibTBDGso5rfENmkabw/edit


class Solution {
    public Node treeToDoublyList(Node root) {
      Node head = null;
      Node prev = null;
      
      Stack<Node> stack = new Stack<>(); // Stack<Node> stack = new LinkedList<>(); why its not correct 
      while(root != null || !stack.isEmpty()){
        while(root != null){
          stack.push(root);
          root = root.left;
        }
        
        root = stack.pop();
        root.left = prev;
        if(prev != null){
          prev.right = root;
        }else{
          head = root;
        }
        Node right = root.right;
        head.left = root;
        root.right = head;
        prev = root;
        root = right;
      }
      return head;
        
    }
}

 

426. Convert Binary Search Tree to Sorted Doubly Linked List

标签:stack   code   nod   amp   arch   document   arc   ||   root   

原文地址:https://www.cnblogs.com/tobeabetterpig/p/9450664.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!