LeetCode(剑指 Offer)- 36. 二叉搜索树与双向链表

Posted 放羊的牧码

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode(剑指 Offer)- 36. 二叉搜索树与双向链表相关的知识,希望对你有一定的参考价值。

题目链接:点击打开链接

题目大意:

解题思路:

相关企业

  • 字节跳动
  • Facebook
  • 亚马逊(Amazon)
  • 微软(Microsoft)

AC 代码

  • Java
/*
// Definition for a Node.
class Node 
    public int val;
    public Node left;
    public Node right;
    public Node() 
    public Node(int _val) 
        val = _val;
    
    public Node(int _val,Node _left,Node _right) 
        val = _val;
        left = _left;
        right = _right;
    
;
*/
 
class Solution 
    Node pre, head;
    public Node treeToDoublyList(Node root) 
        if(root == null) return null;
        dfs(root);
        head.left = pre;
        pre.right = head;
        return head;
    
    void dfs(Node cur) 
        if(cur == null) return;
        dfs(cur.left);
        if(pre != null) pre.right = cur;
        else head = cur;
        cur.left = pre;
        pre = cur;
        dfs(cur.right);
    
  • C++
/*
// Definition for a Node.
class Node 
public:
    int val;
    Node* left;
    Node* right;
    Node() 
    Node(int _val) 
        val = _val;
        left = NULL;
        right = NULL;
    
    Node(int _val, Node* _left, Node* _right) 
        val = _val;
        left = _left;
        right = _right;
    
;
*/
 
class Solution 
public:
    Node* treeToDoublyList(Node* root) 
        if(root == nullptr) return nullptr;
        dfs(root);
        head->left = pre;
        pre->right = head;
        return head;
    
private:
    Node *pre, *head;
    void dfs(Node* cur) 
        if(cur == nullptr) return;
        dfs(cur->left);
        if(pre != nullptr) pre->right = cur;
        else head = cur;
        cur->left = pre;
        pre = cur;
        dfs(cur->right);
    
;

以上是关于LeetCode(剑指 Offer)- 36. 二叉搜索树与双向链表的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode]剑指 Offer 36. 二叉搜索树与双向链表

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

LeetCode(剑指 Offer)- 36. 二叉搜索树与双向链表

*Leetcode 426 & 剑指 Offer 36. 二叉搜索树与双向链表

*Leetcode 426 & 剑指 Offer 36. 二叉搜索树与双向链表

[LeetCode]剑指 Offer 54. 二叉搜索树的第k大节点