刷题感悟 - Convert Binary Search Tree to Doubly Linked List

Posted

tags:

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

将二叉查找树转化成双向链表

 

题目思路其实不难 ,中序遍历,然后再依次的将数据放入链表中即可

重点:新加元素前后链的配置 

有个有意思的地方在于result没有赋初值 导致写代码时需要先初始化 然后删除之 。

/**
 * 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
        if(root==null)return null;
        DoublyListNode rootsult = new DoublyListNode(0);
        midOrder(root,rootsult);
        rootsult = rootsult.next;
        return rootsult;
    }
    
    public void midOrder(TreeNode root,DoublyListNode result){
        if(root.left!=null)midOrder(root.left,result);
        setNode(root.val, result);
        if(root.right!=null)midOrder(root.right,result);
    }
    public void setNode(int val,DoublyListNode result){
        if(result==null) result = new DoublyListNode(val);
        else{
            DoublyListNode node = new DoublyListNode(val);
            while(result.next!=null)result = result.next;
            node.prev=result;
            result.next = node;
        }
    }
}

 

在大数据量的情况下 有可能会爆栈

下一步想想如何用非递归的方法实现之 占坑

 

以上是关于刷题感悟 - Convert Binary Search Tree to Doubly Linked List的主要内容,如果未能解决你的问题,请参考以下文章

convert-sorted-list-to-binary-search-tree

刷题感悟- Binary Tree Path Sum

LeetCode-Easy刷题(23) Convert Sorted Array to Binary Search Tree

leetcode 109 Convert Sorted List to Binary Search Tree

Convert Sorted List to Binary Search Tree

Convert Sorted Array to Binary Search Tree & Convert Sorted List to Binary Search Tree