将二叉查找树转化成双向链表
题目思路其实不难 ,中序遍历,然后再依次的将数据放入链表中即可
重点:新加元素前后链的配置
有个有意思的地方在于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; } } }
在大数据量的情况下 有可能会爆栈
下一步想想如何用非递归的方法实现之 占坑