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

将一个二叉查找树按照中序遍历转换成双向链表

/** * 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 left = bstToDoublyList(root.left); DoublyListNode result = new DoublyListNode(root.val) ; DoublyListNode right = bstToDoublyList(root.right); DoublyListNode temp = left ; if(left!=null){ while(temp.next!=null){ temp = temp.next; } temp.next = result; result.prev = temp; }else{ left = result; } if(right!=null){ result.next = right; right.prev = result; } return left; } }

    原文作者:二叉查找树
    原文地址: https://blog.csdn.net/m0_37664212/article/details/78519204
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞