zoukankan      html  css  js  c++  java
  • leetcode 114. 二叉树展开为链表

    思路

    1、判断左子树是否为空,若为空则直接往右走,若不为空则2
    2、将当前节点root的右子树接到当前root节点的左孩子节点的最右下边的孩子节点
    3、将当前节点root的左子树接到右子树上,并将左节点置为NULL。

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
     *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
     *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
     * };
     */
    class Solution {
    public:
        void flatten(TreeNode* root) {
            if (!root)
            return;
            while(root!=NULL)
            {
    
                if(root->left!=NULL)//判断左子树是否为空
                {
                    TreeNode* p = root->left; // 得到当前根节点的左子树
                    while(p->right!=NULL)//得到当前左子树的最右下边的孩子节点
                    {
                       p = p->right;
                    }
                    p->right = root->right;//将当前节点的右子树接到当前节点的左孩子节点最右下边的孩子节点上
                    root->right = root->left;//将当前接单的左子树接到右子树上
                    root->left=NULL;
                }
                root = root->right;
            }
    
        }
    };
    以大多数人努力程度之低,根本轮不到去拼天赋~
  • 相关阅读:
    POJ 1113 Wall
    POJ 3525 Most Distant Point from the Sea
    POJ 3335 Rotating Scoreboard
    POJ 1228 Grandpa's Estate
    POJ 1873 The Fortified Forest
    POJ 2354 Titanic
    POJ 3130 How I Mathematician Wonder What You Are!
    POJ 1106 Transmitters
    POJ 1474 Video Surveillance
    seajs 的研究一 无题
  • 原文地址:https://www.cnblogs.com/gcter/p/15338593.html
Copyright © 2011-2022 走看看