剑指offer 36. 二叉搜索树与双向链表

剑指offer 36. 二叉搜索树与双向链表

题目描述

在这里插入图片描述
在这里插入图片描述

解题思路

二叉搜索树的中序遍历就是顺序链表。

本题还用到了中序遍历记录前驱的方法。

class Solution {
    
    
    Node head, pre;
    public Node treeToDoublyList(Node root) {
    
    
        if (root == null) return null;
        //将树转化为双向链表,pre最后停留在尾节点上
        inorderTraversal(root);
        //将 双向链表 转化为 双向循环链表
        head.left = pre;
        pre.right = head;
        return head;
    }
    
    //中序遍历,将以root为根节点的树转化为双向链表
    public void inorderTraversal(Node root) {
    
    
        if (root == null) return;
        inorderTraversal(root.left);

        if (pre != null) {
    
    
            pre.right = root;
        } else {
    
    
            head = root;   //双向链表的头结点
        }
        root.left = pre;
        pre = root;   //记录前驱

        inorderTraversal(root.right);
    }
}

猜你喜欢

转载自blog.csdn.net/cys975900334/article/details/115199298