二叉查找树转双向链表JAVA实现

来源:互联网 发布:淘宝允许好评返现吗 编辑:程序博客网 时间:2024/05/31 15:18
把二元查找树转变成排序的双向链表
题目:
输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求不能创建任何新的结点,只调整指针的指向。
10
/ \
6 14
/ \ / \
4 8 12 16
转换成双向链表
4=6=8=10=12=14=16。


/**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;//更新尾结点为当前结点,或者说:尾结点后移       }  }



0 0