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

    简单题

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        TreeNode* flat(TreeNode* root){
            if(root == nullptr) return nullptr;
            TreeNode *left = nullptr , *right = nullptr;
            if(root -> left){
                left = flat(root -> left);
            }
            if(root -> right){
                right = flat(root -> right);
            }
            root -> left = nullptr;
            if(left != nullptr){
                root -> right = left;
            }
            if(right != nullptr){
                if(left){
                    while(left -> right != nullptr){
                        left = left -> right;
                    } 
                    left -> right = right;
                }else{
                    root -> right = right;
                }
            }
            return root;
        }
        void flatten(TreeNode *root) {
          flat(root);
        }
    };

    ----update 2014-07-07---

    class Solution {
    public:
        TreeNode* make(TreeNode* root) {
            if (root == nullptr) return nullptr;
            TreeNode* tRight = root->right;
            TreeNode* ans = root;
            root->right = make(root->left);
            root->left = nullptr;
            while(root->right) {
                root = root->right;
            }
            root->right = make(tRight);
            return ans;
        }
        void flatten(TreeNode *root) {
            make(root);
        }
    };

    重写了下,代码简洁点,不过记得就是要把left的指针指向null

  • 相关阅读:
    python中列表排序的方法
    pyrhon3中字符串方法
    python数据探索与数据与清洗概述
    2020年日期表-python实现
    python中字符串离散化的例子
    python中常见的日期处理方法
    如何简单地理解Python中的if __name__ == '__main__'
    我的老爸老了
    关于
    关于
  • 原文地址:https://www.cnblogs.com/x1957/p/3501155.html
Copyright © 2011-2022 走看看