zoukankan      html  css  js  c++  java
  • leet 114二叉树展开为链表

     解析直接复制官方解释了,参考的第一种思路。自己没想出来啊呜呜

        1
       / 
      2   5
     /    
    3   4   6
    
    //将 1 的左子树插入到右子树的地方
        1
         
          2         5
         /          
        3   4         6        
    //将原来的右子树接到左子树的最右边节点
        1
         
          2          
         /           
        3   4  
             
              5
               
                6
                
     //将 2 的左子树插入到右子树的地方
        1
         
          2          
                     
            3       4  
                     
                      5
                       
                        6   
            
     //将原来的右子树接到左子树的最右边节点
        1
         
          2          
                     
            3      
             
              4  
               
                5
                 
                  6         
      
      ......
    
    作者:windliang
    链接:https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by--26/
    来源:力扣(LeetCode)
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

    然后用C++实现了如下

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
     *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
     *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
     * };
     */
    class Solution {
    public:
        void flatten(TreeNode* root) {
            while(root!=NULL)
            {
                if(root->left==NULL)
                {
                    root=root->right;
                }
                else
                {
                    TreeNode* pre=root->left;
                    while(pre->right!=NULL)
                    {
                        pre=pre->right;
                    }
                    pre->right=root->right;
                    root->right=root->left;
                    root->left=NULL;
                    root=root->right;
                }
            }
        }
    };
  • 相关阅读:
    重写gallery 的 BaseAdapter
    excel数据导入DB
    更换 字体
    Android Activity跳转 Intent
    mpax5.0比mapx4.51多了些什么功能?
    [转载]INET控件的几点使用
    [转载]GIS基本概念集锦
    [转载]Microsoft.XMLHTTP对象
    等值线的绘制
    [转载]关于webbrowser,innet,xmlhttp获取网页源码的比较!
  • 原文地址:https://www.cnblogs.com/libin123/p/13271815.html
Copyright © 2011-2022 走看看