作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/flip-binary-tree-to-match-preorder-traversal/

题目描述

Given a binary tree with N nodes, each node has a different value from {1, …, N}.

A node in this binary tree can be flipped by swapping the left child and the right child of that node.

Consider the sequence of N values reported by a preorder traversal starting from the root. Call such a sequence of N values the voyage of the tree.

(Recall that a preorder traversal of a node means we report the current node’s value, then preorder-traverse the left child, then preorder-traverse the right child.)

Our goal is to flip the least number of nodes in the tree so that the voyage of the tree matches the voyage we are given.

If we can do so, then return a list of the values of all nodes flipped. You may return the answer in any order.

If we cannot do so, then return the list [-1].

Example 1:

Input: root = [1,2], voyage = [2,1]
Output: [-1]

Example 2:

Input: root = [1,2,3], voyage = [1,3,2]
Output: [1]

Example 3:

Input: root = [1,2,3], voyage = [1,2,3]
Output: []

Note:

  1. 1 <= N <= 100

题目大意

最少翻转哪些节点,能使得二叉树的前序遍历变成voyage.

解题方法

前序遍历

其实这个题不难,因为题目就说了是前序遍历,所以做法肯定还是前序遍历。我刚开始一直想不通的地方在于,题目又是返回[-1],又是正常返回,没想好怎么做区分。其实做法就是递归函数不仅要修改res数组,还要返回表示能不能构成题目条件的bool变量。

按照lee215的说法,看到二叉树的题,很大可能就需要递归,所以直接先写出dfs函数,然后再慢慢向里面填东西。

我们定义的dfs函数意义是,我们能不能通过翻转(或者不翻转)该root节点的左右子树,得到对应v。如果能,返回true,否则返回false。

首先在递归函数中,我们对root节点进行判断,如果root不存在,这种情况不应该认为是题目输入错误,而是应该认为已经遍历到最底部了,这个时候相当于root = [], voyage = [],所以返回true;在先序遍历的时候,root节点是第一个要被遍历到的节点,如果不和voyage[0]相等,直接返回false;

这个题目的难点在于是否需要翻转一个节点的左右孩子。判断的方法其实是简单的:如果voyage第二个元素等于root的左孩子,那么说明不用翻转,直接递归调用左右孩子;否则如果voyage的第二个元素等于root的右孩子,那么还要注意一下,在左孩子存在的情况下,我们需要翻转当前的节点左右孩子。

翻转是什么概念呢?这里并没有直接交换,而是把当前遍历到的位置使用遍历i保存起来,这样voyage[i]就表示当前遍历到哪个位置了。所以dfs调用两个孩子的顺序很讲究,它体现了先序遍历先解决哪个树的问题,也就是完成了逻辑上的交换左右孩子。

C++代码如下:

/**
* 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:
int i = 0;
vector<int> res;
vector<int> flipMatchVoyage(TreeNode* root, vector<int>& voyage) {
res.clear();
if (dfs(root, voyage)) {
return res;
}
return {-1};
}
// can we get v by flip root?
bool dfs(TreeNode* root, vector<int>& v) {
if (!root) return true;
if (root->val != v[i++]) return false;
if (root->left && root->left->val == v[i]) {
return dfs(root->left, v) && dfs(root->right, v);
} else if (root->right && root->right->val == v[i]) {
if (root->left)
res.push_back(root->val);
return dfs(root->right, v) && dfs(root->left, v);
}
return !root->left && !root->right;
}
};

参考资料:https://leetcode.com/problems/flip-binary-tree-to-match-preorder-traversal/discuss/214216/JavaC%2B%2BPython-DFS-Solution

日期

2019 年 1 月 6 日 —— 打球打的腰酸背痛

【LeetCode】971. Flip Binary Tree To Match Preorder Traversal 解题报告(C++)的更多相关文章

  1. LeetCode 971. Flip Binary Tree To Match Preorder Traversal

    原题链接在这里:https://leetcode.com/problems/flip-binary-tree-to-match-preorder-traversal/ 题目: Given a bina ...

  2. LC 971. Flip Binary Tree To Match Preorder Traversal

    Given a binary tree with N nodes, each node has a different value from {1, ..., N}. A node in this b ...

  3. [Swift]LeetCode971.翻转二叉树以匹配先序遍历 | Flip Binary Tree To Match Preorder Traversal

    Given a binary tree with N nodes, each node has a different value from {1, ..., N}. A node in this b ...

  4. 【LeetCode】 Binary Tree Zigzag Level Order Traversal 解题报告

    Binary Tree Zigzag Level Order Traversal [LeetCode] https://leetcode.com/problems/binary-tree-zigzag ...

  5. 【LeetCode】144. Binary Tree Preorder Traversal 解题报告(Python&C++&Java)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 迭代 日期 题目地址:https://leetc ...

  6. LeetCode: Binary Tree Preorder Traversal 解题报告

    Binary Tree Preorder Traversal Given a binary tree, return the preorder traversal of its nodes' valu ...

  7. 【一天一道LeetCode】#103. Binary Tree Zigzag Level Order Traversal

    一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 来源: htt ...

  8. leetCode :103. Binary Tree Zigzag Level Order Traversal (swift) 二叉树Z字形层次遍历

    // 103. Binary Tree Zigzag Level Order Traversal // https://leetcode.com/problems/binary-tree-zigzag ...

  9. 【LeetCode】589. N-ary Tree Preorder Traversal 解题报告 (Python&C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 迭代 日期 题目地址:https://leetc ...

随机推荐

  1. PHP对称加密-AES加密、DES加密

    对称加密 对称加密算法是指,数据发信方将明文(原始数据)和密钥一起经过加密处理后,使其变成复杂的加密密文发送出去.收信方收到密文后,若要解读原文,则需要使用加密密钥及相关算法的逆算法对密文进行解密,使 ...

  2. Python Cheatsheet

    Comprehensive Python Cheatsheet Download text file, Buy PDF, Fork me on GitHub or Check out FAQ. Con ...

  3. 暂时lvs

    负载均衡集群是 load balance 集群的简写,翻译成中文就是负载均衡集群.常用的负载均衡开源软件有nginx.lvs.haproxy,商业的硬件负载均衡设备F5.Netscale.这里主要是学 ...

  4. 简单的Mybatis程序

    1.新建一个普通Maven项目,导入 mybatis.mysql.junit(用于测试)3个依赖 Mybatis <dependency> <groupId>org.mybat ...

  5. 零基础学习java------38---------spring中关于通知类型的补充,springmvc,springmvc入门程序,访问保护资源,参数的绑定(简单数据类型,POJO,包装类),返回数据类型,三大组件,注解

    一. 通知类型 spring aop通知(advice)分成五类: (1)前置通知[Before advice]:在连接点前面执行,前置通知不会影响连接点的执行,除非此处抛出异常. (2)正常返回通知 ...

  6. Stream collect Collectors 常用详细实例

    返回List集合: toList() 用于将元素累积到List集合中.它将创建一个新List集合(不会更改当前集合). List<Integer> integers = Arrays.as ...

  7. 队列——Java实现

    1 package struct; 2 3 interface IQueue{ 4 //入队列 5 void add(Object obj); 6 //出队列 7 Object remove(); 8 ...

  8. 【Go】【Basic】MacOS上搭建GO开发环境

    1. GO下载 1.1. 下载地址:https://www.golangtc.com/download (需要科学上网) 1.1.1. PKG安装: 下载这个包:go1.9.2.darwin-amd6 ...

  9. Linux基础命令---mailq显示邮件队列

    mailq mailq指令可以显示出待发送的邮件队列. 此命令的适用范围:RedHat.RHEL.Ubuntu.CentOS.Fedora.   1.语法       mailq   2.选项参数列表 ...

  10. gitlab之数据备份恢复

    备份#备份的时候,先通知相关人员服务要听 ,停止两个服务,并影响访问 root@ubuntu:/opt/web1# gitlab-ctl stop unicorn ok: down: unicorn: ...