• LintCode | 将二叉查找树转换成双向链表


    http://www.lintcode.com/zh-cn/problem/convert-binary-search-tree-to-doubly-linked-list/#

    递归做法:

    1. 分别将BST的左、右子树转换成双向链表
    2. new出一个链表节点,值等于BST根节点的值
    3. 由于是BST,所以new出的节点应该位于链表的中间,所以分别连接左、右子树转换成的链表。这一步中须要找到左链表的尾节点。

    对于一些细节处理,要加上必要的判空语句(链表节点为空时,不能访问它)

    /**
     * Definition of TreeNode:
     * class TreeNode {
     * public:
     *     int val;
     *     TreeNode *left, *right;
     *     TreeNode(int val) {
     *         this->val = val;
     *         this->left = this->right = NULL;
     *     }
     * }
     * Definition of Doubly-ListNode
     * class DoublyListNode {
     * public:
     *     int val;
     *     DoublyListNode *next, *prev;
     *     DoublyListNode(int val) {
     *         this->val = val;
               this->prev = this->next = NULL;
     *     }
     * }
     */
    class Solution {
    public:
        /**
         * @param root: The root of tree
         * @return: the head of doubly list node
         */
        DoublyListNode* bstToDoublyList(TreeNode* root) {
            if (!root) return NULL;
            
            DoublyListNode *left = bstToDoublyList(root->left);
            DoublyListNode *right = bstToDoublyList(root->right);
            
            DoublyListNode *left_tail = left;
            while (left_tail && left_tail->next) left_tail = left_tail->next;
            
            DoublyListNode *cur = new DoublyListNode(root->val);
            cur->prev = left_tail;
            if (left_tail) left_tail->next = cur;
            cur->next = right;
            if (right) right->prev = cur;
            
            if (left) return left;
            else return cur;
        }
    };
    
  • 相关阅读:
    pyinstaller相关用法
    yield 与 yield from
    async /await相关知识理解
    调试程序方法pdb
    任务22-4
    任务22-2
    跳台阶
    计算三维空间某点距离原点的欧式距离
    质数判断
    罗马数字转换
  • 原文地址:https://www.cnblogs.com/ilovezyg/p/6388375.html
Copyright © 2020-2023  润新知