zoukankan      html  css  js  c++  java
  • 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.
    Flipped Trees Diagram
    

    Note:

    1. Each tree will have at most 100 nodes.
    2. 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 }
  • 相关阅读:
    Android开发学习笔记-关于Android的消息推送以及前后台切换
    C#文件操作工具类
    c#取得应用程序根目录
    Visual Studio 2012中使用GitHub
    C#邮件发送
    jquery判断某个属性是否存在 hasAttr
    js 如何让两个等长的数组产生键值对关系
    js判断一个元素是否在数组中
    日期控件
    react 生命周期函数的一些心得体会
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/11072771.html
Copyright © 2011-2022 走看看