LeetCode 951. Flip Equivalent Binary Trees
Posted dylan-java-nyc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 951. Flip Equivalent Binary Trees相关的知识,希望对你有一定的参考价值。
原题链接在这里:https://leetcode.com/problems/flip-equivalent-binary-trees/
题目:
For a binary tree T, we can define a flip operation as follows: choose any node, and swap the left and right child subtrees.
A binary tree X is flip equivalent to a binary tree Y if and only if we can make X equal to Y after some number of flip operations.
Write a function that determines whether two binary trees are flip equivalent. The trees are given by root nodes root1
and root2
.
Example 1:
Input: root1 = [1,2,3,4,5,6,null,null,null,7,8], root2 = [1,3,2,null,6,4,5,null,null,null,null,8,7]
Output: true
Explanation: We flipped at nodes with values 1, 3, and 5.
Note:
- Each tree will have at most
100
nodes. - Each value in each tree will be a unique integer in the range
[0, 99]
.
题解:
Compare root1 and root2, see if it is equal first.
If yes, then
Case 1: root1.left equivalent to root2.left && root1.right equivalent to root2.right
Case 2: root1.left equivalent to root2.right && root1.right equivalent to root2.left.
Either case is true, then return true.
Time Complexity: O(n^2). T(n) = 4*T(n/2) + 1. Master Theorem, T(n) = O(n^2).
Space: O(h).
AC Java:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) val = x; 8 * 9 */ 10 class Solution 11 public boolean flipEquiv(TreeNode root1, TreeNode root2) 12 if(root1 == null && root2 == null) 13 return true; 14 15 16 if(root1 == null || root2 == null) 17 return false; 18 19 20 if(root1.val != root2.val) 21 return false; 22 23 24 return (flipEquiv(root1.left, root2.left) && flipEquiv(root1.right, root2.right)) 25 || (flipEquiv(root1.left, root2.right) && flipEquiv(root1.right, root2.left)); 26 27
以上是关于LeetCode 951. Flip Equivalent Binary Trees的主要内容,如果未能解决你的问题,请参考以下文章
[LC] 951. Flip Equivalent Binary Trees