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

    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

    算法:该题用的是递归,只要考虑当前节点,思路如下,设当前节点为root,把root的左节点的最右节点的右子树指向root的右子树,然后把root的右指针指向root的左子树,root的做指针置空,下一个节点处理root->right,代码如下:

     1 /**
     2  * Definition for binary tree
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     void flatten(TreeNode *root) {
    13         if(NULL==root)  return;
    14         if(NULL!=root->left)
    15         {
    16             getLeftRight(root)->right=root->right;
    17             root->right=root->left;
    18             root->left=NULL;
    19         }
    20         flatten(root->right);
    21         
    22     }
    23     
    24     TreeNode* getLeftRight(TreeNode* root)
    25     {
    26         root=root->left;
    27         while(NULL!=root->right)  root=root->right;
    28         return root;
    29     }
    30 };
  • 相关阅读:
    hdu3613(扩展KMP)
    hdu4333(扩展KMP)
    poj 2185
    指数型母函数
    java高精度hdu4043
    卡特兰数简单应用
    hdu3625(第一类斯特林数)
    卡特兰数和斯特林数(转载)
    hdu4045(递推)
    java 中sendredirect()和forward()方法的区别
  • 原文地址:https://www.cnblogs.com/sqxw/p/3970366.html
Copyright © 2011-2022 走看看