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

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

    For example, given the following tree:

        1
       / 
      2   5
     /    
    3   4   6
    

    The flattened tree should look like:

    1
     
      2
       
        3
         
          4
           
            5
             
              6

    将一个二叉树重组成一个链表

    题目要求按照二叉树的先序遍历的顺序重组二叉树

    思路1:

    找到最左侧结点,将其父结点与父结点右结点断开,将其连接至父结点右侧,变成父结点的右结点,然后把原右结点插入到新右结点的右侧。递归这一操作即可

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

    思路2:

    从根结点出发,判断其左结点是否存在,如果存在,则将根结点与其右结点断开,根的左结点变成其右结点。在将右结点链接至左结点最右边的右结点处。

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        void flatten(TreeNode* root) {
            if (!root)
                return;
            TreeNode* curr = root;
            while (curr)
            {
                if (curr->left)
                {
                    TreeNode* temp = curr->left;
                    while (temp->right)
                        temp = temp->right;
                    temp->right = curr->right;
                    curr->right = curr->left;
                    curr->left = NULL;
                }
                curr = curr->right;
            }
        }
    };
  • 相关阅读:
    linux常用命令
    ANAFI EXTENOED无人机(1)环境配置和基础开发
    无人机自主降落
    ROS开发(1)安装环境
    bebop无人机(1)环境配置和基础开发
    YOLO标注软件
    Python2与Python3之间切换
    python实现IOU计算
    读取多个(海康大华)网络摄像头的视频流 (使用opencv-python),解决实时读取延迟问题
    如何到外面的世界看看
  • 原文地址:https://www.cnblogs.com/immjc/p/9076162.html
Copyright © 2011-2022 走看看