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

    递归的思想,左子树整理成一条链,右子树整理成一条链,然后左子树的尾节点链上右子树的头节点就好了

     1 #include <iostream>
     2 using namespace std;
     3 struct TreeNode {
     4     int val;
     5     TreeNode  *left;
     6     TreeNode  *right;
     7     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8 };
     9 class Solution {
    10 public:
    11     void flatten(TreeNode *root) {
    12         if(root == NULL) return;
    13         flattenTree(root);
    14     }
    15     TreeNode *flattenTree(TreeNode *root){
    16         if(root == NULL) return NULL;
    17         if(root->left == NULL && root->right == NULL) return root;
    18         TreeNode *lefthead,*righthead;
    19         righthead = lefthead = NULL;
    20         if(root->left != NULL) lefthead = flattenTree(root->left);
    21         if(root->right != NULL) righthead = flattenTree(root->right);
    22         if(lefthead == NULL) root->right = righthead;
    23         if(righthead == NULL) root->right = lefthead;
    24         if(lefthead != NULL && righthead != NULL){
    25             root->right = lefthead;
    26             TreeNode *leftTail = getTail(lefthead);
    27             leftTail->right = righthead;
    28         }
    29         root->left = NULL;
    30         return root;
    31     }
    32     TreeNode *getTail(TreeNode *root){
    33         if(root == NULL) return NULL;
    34         while(root->right != NULL) root = root->right;
    35         return root;
    36     }
    37 };
    艰难的成长
  • 相关阅读:
    数据结构之树和二叉树的一些基本概念
    面向对象的三大特点
    WOJ 1020
    C++ STL copy函数效率分析
    局部特化和类模板成员特化
    局部特化 & 特化
    back_inserter 与 iterator
    new期间的异常
    数组分配
    placement new和delete
  • 原文地址:https://www.cnblogs.com/marylins/p/3608166.html
Copyright © 2011-2022 走看看