zoukankan      html  css  js  c++  java
  • Flatten Binary Tree to Linked List

    题目:

    Given a binary tree, flatten it to a linked list in-place.

    For example,
    Given

             1
            / 
           2   5
          /    
         3   4   6
    

    The flattened tree should look like:

       1
        
         2
          
           3
            
             4
              
               5
                
                 6

    其实就是把二叉树按前序遍历顺序以右指针为next搞成一个单链表,想了半天前驱、后继貌似没折,后来想把左子树先平掉,再把左子树合到右子树顶端之上,再平掉原先右子树的那个结点为根的树即可。代码如下:

     1     void flatten(TreeNode *root) {
     2         if(root==NULL) return;
     3         TreeNode* t,*right=root->right;
     4         flatten(root->left);//平掉左子树
     5         if(root->left){//把左子树插入到右子树与根之间
     6             t = root->left;
     7             while(t&&t->right) t=t->right;
     8             right = t->right = root->right;
     9             root->right=root->left;
    10             root->left=NULL;
    11         }
    12         flatten(right);//平掉右子树
    13     }
  • 相关阅读:
    Hive
    Hadoop简介与分布式安装
    Hadoop分布式文件系统HDFS
    HDFS的操作SHELL和API
    HDFS高级功能
    Yarn
    Hadoop的I/O操作
    Hadoop的RPC工作原理
    Mapreduce入门和优化方案
    MapReduce的工作机制
  • 原文地址:https://www.cnblogs.com/mike442144/p/3426326.html
Copyright © 2011-2022 走看看