本文共 912 字,大约阅读时间需要 3 分钟。
把二元查找树转变成排序的双向链表/**public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; }}*/public class Solution { private TreeNode head=null; private TreeNode tail=null; public TreeNode Convert(TreeNode pRootOfTree) { visit(pRootOfTree); return head; } public void visit(TreeNode root) { if (root == null) { return; } visit(root.left); createList(root); visit(root.right); } public void createList(TreeNode cur){ cur.left=tail;//把当前的节点接到链表的尾部 if(tail!=null){//双向连接 tail.right=cur; }else{ head=cur; } tail=cur;//更新尾结点为当前结点,或者说:尾结点后移 } }
转载地址:http://fomvb.baihongyu.com/