LeetCode 1516. Move Sub-Tree of N-Ary Tree(DFS)

文章目录

    • 1. 题目
    • 2. 解题

1. 题目

Given the root of an N-ary tree of unique values, and two nodes of the tree p and q.

You should move the subtree of the node p to become a direct child of node q. If p is already a direct child of q, don’t change anything. Node p must be the last child in the children list of node q.

Return the root of the tree after adjusting it.

There are 3 cases for nodes p and q:

  • Node q is in the sub-tree of node p.
  • Node p is in the sub-tree of node q.
  • Neither node p is in the sub-tree of node q nor node q is in the sub-tree of node p.

In cases 2 and 3, you just need to move p (with its sub-tree) to be a child of q, but in case 1 the tree may be disconnected, thus you need to reconnect the tree again. Please read the examples carefully before solving this problem.

Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).
在这里插入图片描述
For example, the above tree is serialized as [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14].

Example 1:
在这里插入图片描述

Input: root = [1,null,2,3,null,4,5,null,6,null,7,8], p = 4, q = 1
Output: [1,null,2,3,4,null,5,null,6,null,7,8]
Explanation: This example follows the second case as node p is in the sub-tree of node q. We move node p with its sub-tree to be a direct child of node q.
Notice that node 4 is the last child of node 1.

Example 2:
在这里插入图片描述

Input: root = [1,null,2,3,null,4,5,null,6,null,7,8], p = 7, q = 4
Output: [1,null,2,3,null,4,5,null,6,null,7,8]
Explanation: Node 7 is already a direct child of node 4. We don’t change anything.

Example 3:
在这里插入图片描述

Input: root = [1,null,2,3,null,4,5,null,6,null,7,8], p = 3, q = 8
Output: [1,null,2,null,4,5,null,7,8,null,null,null,3,null,6]
Explanation: This example follows case 3 because node p is not in the sub-tree of node q and vice-versa. We can move node 3 with its sub-tree and make it as node 8’s child.

Example 4:
在这里插入图片描述

Input: root = [1,null,2,3,null,4,5,null,6,null,7,8], p = 2, q = 7
Output: [1,null,7,3,null,2,null,6,null,4,5,null,null,8]
Explanation: Node q is in the sub-tree of node p, so this is case 1.
The first step, we move node p (with all of its sub-tree except for node q) and add it as a child to node q.
Then we will see that the tree is disconnected, you need to reconnect node q to replace node p as shown.

Example 5:
在这里插入图片描述

Input: root = [1,null,2,3,null,4,5,null,6,null,7,8], p = 1, q = 2
Output: [2,null,4,5,1,null,7,8,null,null,3,null,null,null,6]
Explanation: Node q is in the sub-tree of node p, so this is case 1.
The first step, we move node p (with all of its sub-tree except for node q) and add it as a child to node q.
As node p was the root of the tree, node q replaces it and becomes the root of the tree.

Constraints:
The total number of nodes is between [2, 1000].
Each node has a unique value.
p != null
q != null
p and q are two different nodes (i.e. p != q).

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/move-sub-tree-of-n-ary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 解题

  • 先看下 p 在不在 q 的直接子节点里,在的话直接返回
  • 再 DFS 确定 q 是不是 p 的子树节点,以及找到 p\q 的父节点
  • 再分两种情况讨论,见注释
/*
// Definition for a Node.
class Node {
public:int val;vector<Node*> children;Node() {}Node(int _val) {val = _val;}Node(int _val, vector<Node*> _children) {val = _val;children = _children;}
};
*/class Solution {Node *pf = NULL, *qf = NULL;//父节点bool qisSubOfp = false;bool foundp = false;bool foundq = false;
public:Node* moveSubTree(Node* root, Node* p, Node* q) {for(auto node : q->children)if(node == p)//p是q的直接子节点,无需操作return root;Node* empty = new Node(-1);//建立空节点方便处理empty->children.push_back(root);dfs(empty, NULL, p, q);//q 不是 p 的子节点,p肯定不是rootif(!qisSubOfp){//找到 pf 子节点 p 的 iterauto it = find(pf->children.begin(),pf->children.end(),p);pf->children.erase(it);//删除之q->children.push_back(p);//p接到q的子节点中return root;}//q 是 p 的子树节点,p可能是rootauto it = find(qf->children.begin(),qf->children.end(),q);qf->children.erase(it);//断开 q 与 qfit = find(pf->children.begin(),pf->children.end(),p);//断开 p 与 pfit = pf->children.erase(it);//it指向下一个,即 pf child 中 p 的下一个位置q->children.push_back(p);//接入到q下面pf->children.insert(it, q);//pf 的子节点 原来 p 的位置 插入 qreturn empty->children[0];}void dfs(Node* root, Node* fa, Node* p, Node* q){if(!root) return;if(root == p){pf = fa;foundp = true;}if(root == q){if(foundp)qisSubOfp = true;qf = fa;foundq = true;}for(auto c : root->children)dfs(c, root, p, q);if(root == p)foundp = false;//回溯if(root == q)foundq = false;//回溯}   
};

84 ms 28.9 MB


我的CSDN博客地址 https://michael.blog.csdn.net/

长按或扫码关注我的公众号(Michael阿明),一起加油、一起学习进步!
Michael阿明

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/474965.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

空气质量指数(AQI)分析与预测

文章目录前言一、背景Ⅰ数据来源Ⅱ 数据背景Ⅲ 分析目的二、数据探索性分析Ⅰ 数据类型Ⅱ 描述性统计Ⅲ 数据预处理1.缺失值处理1&#xff09;删除缺失值2&#xff09;均值/中值填充2.异常值处理3.重复值处理三、数据分析Ⅰ空气质量排名Ⅱ 全国空气质量1.全国空气质量等级统计2…

如果程序跑着跑着就崩溃了,查看内存

程序跑的时间长就发生中断。 启动任务管理器&#xff0c;选择“进程”选项卡&#xff0c;查看程序的内存。 发现程序运行的过程中内存不断增长。 那么原因可能是运行过程中不断地分配了新的内存而没有释放。 查找的方法是注释代码&#xff0c;然后看内存是不是还在增长&#xf…

LeetCode MySQL解题目录

已完成的 LeetCode MySQL 数据库题目。点击查看我的 LeetCode 算法解题目录。 已解决 123/123 - 简单 54 中等 51 困难 18 前置入门学习 MySQL 基本查询、条件查询、投影查询MySQL 排序、分页查询、聚合查询MySQL 多表查询、连接查询&#xff08;内连接、外连接&#xff09;…

Anaconda3使用过程中遇到的问题

文章目录数据可视化中文、负号显示Anaconda使用pyecharts安装方法方法一&#xff1a;pip install pyecharts安装方法二&#xff1a;清华镜像安装方法三&#xff1a;离线安装成功安装后遇到的问题成功安装却不能使用不能使用某一个图&#xff1a;bar\grid决策树sklearn.exceptio…

AliasDB:简单统一灵活的数据库访问库(支持MSSQL/MySQL/SQLite/Oracle/ODBC/OleDb)适用于中小型系统...

数据库访问各种规模的应用程序不可避免的操作&#xff0c;.NET对提供了简单方便统一的数据库访问类&#xff0c;并且通过Enterprise Lib提供了更为顶层的数据库访问库。在我的人个工作中&#xff0c;现在用得最多的就是通过“动码代码生成器”对一次性生成数据库访问接口&#…

数据分析方法--回归分析方法((SPSS建模:多元线性回归案例)

文章目录回归定义最常用回归方法一、线性回归(Linear Regression)二、逻辑回归(Logistic Regression)三、多项式回归(Polynomial Regression)四、逐步回归(Stepwise Regression)五、岭回归(Ridge Regression)六、套索回归(Lasso Regression)七、回归(ElasticNet)如何正确选择回…

LeetCode MySQL 1511. Customer Order Frequency

文章目录1. 题目2. 解题1. 题目 Table: Customers ------------------------ | Column Name | Type | ------------------------ | customer_id | int | | name | varchar | | country | varchar | ------------------------ customer_id is the p…

LeetCode MySQL 1075. 项目员工 I

文章目录1. 题目2. 解题1. 题目 项目表 Project&#xff1a; ---------------------- | Column Name | Type | ---------------------- | project_id | int | | employee_id | int | ---------------------- 主键为 (project_id, employee_id)。 employee_id 是员…

The Shapes of CSS

http://home.cnblogs.com/blog/转载于:https://www.cnblogs.com/yanyanhappy/archive/2012/09/07/2675050.html

数据分析-书籍整理(一)

入门书籍 《谁说菜鸟不会数据分析》讲解了一些常见的分析技巧&#xff0c;并附带 Excel 的一些知识以及职场可使用的基础数据分析。 《MYSQL必知必会》对于有sql基础的人来说&#xff0c;可以快速复习知识点&#xff0c;小白也能学习到很多&#xff0c;不会打击自信心。我是用…

hdu 1054 Strategic Game 最小点覆盖 = 最大二分匹配

题目地址&#xff1a;http://acm.hdu.edu.cn/showproblem.php?pid1054 简单二分匹配&#xff0c;根据题意构造一个无向图。然后求最小点覆盖&#xff0c;然后扫描mark数组将曾经匹配的点所匹配的边消去。 最小点覆盖 最大二分匹配 #include<stdio.h> #include<strin…

数据分析统计学基础一

文章目录数据分析方法分类1、单纯的数据加工方法2、基于数理统计的数据分析方法3、基于数据挖掘的数据分析方法4、基于大数据的数据分析方法描述性统计分析1、数据的计量尺度2、数据的集中趋势3、数据的离中趋势4、数据分布的测定正态分布a. 偏态系数b. 数据峰度c. 偏度与峰度的…

LeetCode MySQL 1435. 制作会话柱状图

文章目录1. 题目2. 解题1. 题目 表&#xff1a;Sessions ------------------------------ | Column Name | Type | ------------------------------ | session_id | int | | duration | int | ------------------------------ sessio…

SharePoint2010网站备份还原简单介绍

今天尝试了SharePoint2010网站的备份和还原&#xff0c;从网上搜一些文档看看&#xff0c;然后自己试试&#xff0c;感觉和2007的操作没什么太大的区别&#xff0c;跟大家分享下自己尝试的命令行方式和数据库的方式&#xff0c;2007自己常用的也是这两种方式。 1、 命令行的方式…

LeetCode MySQL 1211. 查询结果的质量和占比

文章目录1. 题目2. 解题1. 题目 查询表 Queries&#xff1a; ---------------------- | Column Name | Type | ---------------------- | query_name | varchar | | result | varchar | | position | int | | rating | int | ---------------------…

数据分析方法-聚类算法

文章目录一、定义二、聚类、分类区别分类三、聚类常用算法1.划分聚类 k-means、k-medoids、k-modes、k-medians、kernel k-means2.层次聚类 Agglomerative 、divisive、BIRCH、ROCK、Chameleon3.密度聚类 DBSCAN、OPTICS5.模型聚类 GMM6.图聚类 Spectral Clustering&#xff08…

Java6 WebService学习

参考了网络上中资料&#xff0c;自己学习实践了一个Java6 WebService. 首先&#xff0c;建立一个WebService: package garfield;import javax.jws.WebService;import javax.xml.ws.Endpoint;WebServicepublic class MyJ6WebService {public String SayHello(String strName) {r…

公司人员离职情况分析及预测(工具:python)

前言 目前社会上呈现出一种公司招不到人&#xff0c;大批失业人员的矛盾现象&#xff0c;且大部分公司的离职率居高不下&#xff0c;很多入职没多久就辞职&#xff0c;所花费的培训招聘等资源都浪费了。为了弄清楚公司员工离职原因&#xff0c;通过kaggle上某一家企业员工离职…

LeetCode MySQL 1241. 每个帖子的评论数

文章目录1. 题目2. 解题1. 题目 表 Submissions 结构如下&#xff1a; ------------------------- | 列名 | 类型 | ------------------------- | sub_id | int | | parent_id | int | ------------------------- 上表没有主键, 所以可能…

MYSQL快速导入大量数据

创建数据表&#xff0c;并导入 1.根据数据特征建表&#xff0c;create语句 2.语句导入数据 LOAD DATA INFILE D:/UsersBehavior.csv INTO TABLE users CHARACTER SET utf8 FIELDS TERMINATED BY , OPTIONALLY ENCLOSED BY " ESCAPED BY " LINES TERMINATE…