剑指Offer:面试题27——二叉搜索树与双向链表(java实现)

来源:互联网 发布:羊绒衫怎么洗 知乎 编辑:程序博客网 时间:2024/05/20 02:21

问题描述:

输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。

思路:

将树分为三部分:左子树,根结点,右子树。
1.我们要把根结点与左子树的最大结点连接起来
2.要把根结点与右子树的最小结点连接起来。

代码:(本来按照书上的写的代码,可是得到的结果不对)(下面的代码是他人的代码)

/**public class TreeNode {    int val = 0;    TreeNode left = null;    TreeNode right = null;    public TreeNode(int val) {        this.val = val;    }}*/public class Solution {        TreeNode head = null;    TreeNode realHead = null;    public TreeNode Convert(TreeNode pRootOfTree) {        ConvertSub(pRootOfTree);        return realHead;    }    private void ConvertSub(TreeNode pRootOfTree) {        if(pRootOfTree==null) return;        ConvertSub(pRootOfTree.left);        if (head == null) {            head = pRootOfTree;            realHead = pRootOfTree;        } else {            head.right = pRootOfTree;            pRootOfTree.left = head;            head = pRootOfTree;        }        ConvertSub(pRootOfTree.right);    }}
0 0