标签:todo strong ISE ret 循环双向链表 div while link main
package JianZhioffer; //剑指 Offer 36. 二叉搜索树与双向链表 /** * 输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的循环双向链表。要求不能创建任何新的节点,只能调整树中节点指针的指向。 */ //中序遍历,二叉搜索树,中序遍历从小到大 import java.util.LinkedList; import java.util.Queue; public class test36 { static class Node { public int val; public Node left; public Node right; public Node() {} public Node(int _val) { val = _val; } public Node(int _val,Node _left,Node _right) { val = _val; left = _left; right = _right; } }; public static void main(String[] args) { Node root=new Node(4); root.left=new Node(2); root.right=new Node(5); root.left.left=new Node(1); root.left.right=new Node(3); Node result=treeToDoublyList(root); } public static Node treeToDoublyList(Node root) { if(root==null){ return null; } Queue<Node> q=new LinkedList<>(); dfs(root, q); Node head=q.poll(); Node pre=head,curr=null; while(!q.isEmpty()){ curr=q.poll(); curr.left=pre; pre.right=curr; curr=curr.right; pre=pre.right; } head.left=pre; pre.right=head; return head; } public static void dfs(Node root,Queue<Node> que){ if(root==null){ return; } dfs(root.left, que); que.offer(root); dfs(root.right, que); } }
标签:todo strong ISE ret 循环双向链表 div while link main
原文地址:https://www.cnblogs.com/jieyi/p/14272681.html