426. Convert Binary Search Tree to Sorted Doubly Linked List

Posted tobeabetterpig

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了426. Convert Binary Search Tree to Sorted Doubly Linked List相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

426. Convert Binary Search Tree to Sorted Doubly Linked List - Medium

LeetCode 426. Convert Binary Search Tree to Sorted Doubly Linked List

[leetcode]426. Convert Binary Search Tree to Sorted Doubly Linked List二叉搜索树转有序双向链表

109. Convert Sorted List to Binary Search Tree

108. Convert Sorted Array to balanced Binary Search Tree

108. Convert Sorted Array to Binary Search Tree