Convert Binary Search Tree to Doubly Linked List

Convert a binary search tree to doubly linked list with in-order traversal.
Example
Given a binary search tree:
    4
   /  \
  2   5
  / \
1   3
return 1<->2<->3<->4<->5

我的思路还是追求逻辑最简单,思路最Straightforward但最不容易出错的“傻壮”方法。先求出inorder traversal的ArrayList, 然后将ArrayList转换成Doubly Linked List.

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 * Definition for Doubly-ListNode.
 * public class DoublyListNode {
 *     int val;
 *     DoublyListNode next, prev;
 *     DoublyListNode(int val) {
 *         this.val = val;
 *         this.next = this.prev = null;
 *     }
 * }
 */ 
public class Solution {
    /**
     * @param root: The root of tree
     * @return: the head of doubly list node
     */
    public DoublyListNode bstToDoublyList(TreeNode root) {  
        // Write your code here
        // brute force: first do inOrder traversal, then convert the 
        // list to a doubly linked list
        List<Integer> inOrder = new ArrayList<>();
        if (root == null){
            return null;    
        }
        TreeNode curt = root;
        Stack<TreeNode> stack = new Stack<>();
        while (curt != null){
            stack.push(curt);
            curt = curt.left;
        }
        while (!stack.isEmpty()){
            TreeNode node = stack.pop();
            inOrder.add(node.val);
            curt = node.right;
            while (curt != null){
                stack.push(curt);
                curt = curt.left;
            }
        }
        DoublyListNode res = new DoublyListNode(0);
        res.prev = null;
        DoublyListNode dummy = res;
        if (inOrder.size() == 1){
            return new DoublyListNode(inOrder.get(0));
        }
        for (int i = 0; i < inOrder.size() - 1; i++){
            DoublyListNode curtNode = new DoublyListNode(inOrder.get(i));
            DoublyListNode nextNode = new DoublyListNode(inOrder.get(i + 1));
            curtNode.next = nextNode;
            nextNode.prev = curtNode;
            res.next = curtNode;
            curtNode.prev = res;
            res = res.next;
        }
        return dummy.next;
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,357评论 0 33
  • LeetCode 刷题随手记 - 第一部分 前 256 题(非会员),仅算法题,的吐槽 https://leetc...
    蕾娜漢默阅读 18,204评论 2 36
  • 94. Binary Tree Inorder Traversal 中序 inorder:左节点->根节点->右节...
    Morphiaaa阅读 3,833评论 0 0
  • 目录 简书的 markdown 都不支持 [TOC] 语法……我就不贴目录了。下面按照类别,列出了29道关于二叉树...
    被称为L的男人阅读 8,643评论 0 8
  • 生活就是会有很多琐碎之事,而我们需要做的就是从处理这些琐碎之事中锻炼自己。学习是一生都要做的事情。没有绝对的十全十...
    L雁小七阅读 1,625评论 1 0

友情链接更多精彩内容