/** * 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 */ private static DoublyListNode nodeList=null; public DoublyListNode bstToDoublyList(TreeNode root) { // Write your code here if(root==null) return null; recursion(root); return nodeList; } public void recursion(TreeNode root) { if(root==null) return; recursion(root.right);//因为nodeList最后是移动末节点,所以从右边开始递归,这样nodeList就会变成最初的节点 DoublyListNode node=new DoublyListNode(root.val); node.next=nodeList; if(nodeList!=null){ nodeList.prev=node; } nodeList=node; recursion(root.left); } }