Leetcode 971. Flip Binary Tree To Match Preorder Traversal
Posted 逆風的薔薇
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 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 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 <= N <= 100
分析
以前序遍历二叉树,求能匹配对应序列时需交换左右子树的最少节点集。
考察深度优先搜索。
代码
/**
* Definition for a binary tree node.
* public class TreeNode
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) val = x;
*
*/
class Solution
public List<Integer> flipMatchVoyage(TreeNode root, int[] voyage)
List<Integer> flipPath = new ArrayList<>();
int resultIdx = dfs(root, 0, flipPath, voyage);
if (resultIdx == -1 || resultIdx < voyage.length-1)
return Arrays.asList(-1);
return flipPath;
public int dfs(TreeNode root, int idx, List<Integer> flipPath, int[] voyage)
if (root == null)
return idx;
if (idx >= voyage.length)
return -1;
if(root.val != voyage[idx])
return -1;
int left = dfs(root.left, idx + 1, flipPath, voyage);
if (left != -1)
//Completed the leaf node in left child, then right child
return dfs(root.right, left, flipPath, voyage);
//Need to flip
flipPath.add(root.val);
int right = dfs(root.right, idx + 1, flipPath, voyage);
if (right != -1)
return dfs(root.left, right, flipPath, voyage);
return -1;
以上是关于Leetcode 971. Flip Binary Tree To Match Preorder Traversal的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 951. Flip Equivalent Binary Trees
leetcode951. Flip Equivalent Binary Trees