二叉搜索树与双向链表

二叉搜索树与双向链表

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


设置两个节点,一个是开头,一个是处理的当前,然后递归地中序遍历,遍历中的处理就是处理当前节点和处理的当前的关系。最后输出开头节点

/**
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 temp=null;
    public void convert(TreeNode root){
        if(root==null){
            return;
        }
        convert(root.left);
        /**
        第一次的时候给他们赋值,是最左节点
        **/
        if(head==null){
            head=root;
        }
        if(temp==null){
            temp=root;
        }else{
            temp.right=root;
            root.left=temp;
            temp=root;
        }
        /**
        这里要注意,因为每次执行完temp=root之后,root就变成了root.right,所以每次root都是temp的右子节点
        这是执行temp.right=root;root.left=temp;的原因所在
        **/
        convert(root.right);
    }
     public TreeNode Convert(TreeNode pRootOfTree) {
         convert(pRootOfTree);
         return head;
     }
}
posted @ 2020-03-05 16:09  别再闹了  阅读(48)  评论(0)    收藏  举报