题目描述

输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
 
 
题目链接:
 
 
 
关键点:
更新当前节点时,不需要关心下一个节点,只需要知道前一个节点,利用前一个节点维护向右的关系。
 
分析:
中序遍历,加一个维护前一个节点的变量,始终维护当前节点与前一个节点,来实现树转化成列表。
 
 
 
/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    TreeNode head;
    TreeNode pre = null;
    public TreeNode Convert(TreeNode pRootOfTree) {
         if(null == pRootOfTree){
             return null;
         }
        transport(pRootOfTree);
        return head;
    }
    
    public void transport(TreeNode cur){
        //左节点不为空,则一直往下找
        if(cur.left != null){
            transport(cur.left);
        }
        //更新当前节点的左边位置
        cur.left = pre;
        //更新上一个节点的右边位置。只有第一个节点没有左节点
        if(pre != null){
            pre.right = cur;
        }else{
            //只有第一个节点没有左节点。 存一下链表头
            head = cur;
        }
        //将当前节点更新为前一个节点
        pre = cur;
        //更新右子树
        if(cur.right != null){
            transport(cur.right);
        }
    }
}

 

posted on 2020-06-06 23:14  MoonBeautiful  阅读(225)  评论(0编辑  收藏  举报