zoukankan      html  css  js  c++  java
  • 二叉搜索树转双向链表

    直接通过中序遍历来解。但是需要设置两个节点记录每个子树排序后的第一和最后一个节点,尤其是最后一个,因为最后一个节点是由于连接所需。

    上代码:

    class Solution {
    public:
       
        TreeNode* Convert(TreeNode* pRootOfTree)
        {
            TreeNode* head=NULL;//每个子树排序后的第一个节点
            TreeNode* tail=NULL;//每个子树排序后的最后一个节点
            ConvertHelp(pRootOfTree,head,tail);
            return head;
        }
     void ConvertHelp(TreeNode* pRootOfTree,TreeNode* &head,TreeNode* &tail) {
         if(pRootOfTree==NULL) return;
         ConvertHelp(pRootOfTree->left,head,tail);
         if (tail == NULL) {//说明找到了中序遍历的第一个节点,把其作为链表头节点
             tail = pRootOfTree;
             head = pRootOfTree;
         } else {
             tail->right = pRootOfTree;
             pRootOfTree->left = tail;
             tail = pRootOfTree;
         }
         ConvertHelp(pRootOfTree->right,head,tail);
        }
    };

    法二:(思路同上,但是更简洁)

    class Solution {
    public:
        TreeNode* Convert(TreeNode* pRootOfTree)
        {
            if(pRootOfTree == nullptr) return nullptr;
            TreeNode* pre = nullptr;
             
            convertHelper(pRootOfTree, pre);
             
            TreeNode* res = pRootOfTree;
            while(res ->left)
                res = res ->left;
            return res;
        }
         
        void convertHelper(TreeNode* cur, TreeNode*& pre)
        {
            if(cur == nullptr) return;
             
            convertHelper(cur ->left, pre);
             
            cur ->left = pre;
            if(pre) pre ->right = cur;
            pre = cur;
             
            convertHelper(cur ->right, pre);
             
             
             
        }
    };
  • 相关阅读:
    Building a flexiable renderer
    Indirect Illumination in mental ray
    我的心情
    Cellular Automata
    Subsurface Scattering in mental ray
    Shader Types in mental ray
    BSP Traversal
    我的渲染器终于达到了MR的速度
    How to handle displacement and motion blur
    说明
  • 原文地址:https://www.cnblogs.com/inception6-lxc/p/9276684.html
Copyright © 2011-2022 走看看