zoukankan      html  css  js  c++  java
  • Tweaked Identical Binary Trees

    Determine whether two given binary trees are identical assuming any number of ‘tweak’s are allowed. A tweak is defined as a swap of the children of one node in the tree.

    Examples

            5

          /    

        3        8

      /  

    1      4

    and

            5

          /    

        8        3

               /  

              1     4

    the two binary trees are tweaked identical.

    How is the binary tree represented?

    We use the level order traversal sequence with a special symbol "#" denoting the null node.

    For Example:

    The sequence [1, 2, 3, #, #, 4] represents the following binary tree:

        1

      /  

     2     3

          /

        4

    time: O(4 ^ log_2(n)) = O(n ^ 2), space: O(h)

    /**
     * public class TreeNode {
     *   public int key;
     *   public TreeNode left;
     *   public TreeNode right;
     *   public TreeNode(int key) {
     *     this.key = key;
     *   }
     * }
     */
    public class Solution {
      public boolean isTweakedIdentical(TreeNode one, TreeNode two) {
        // Write your solution here
        if(one == null && two == null) {
          return true;
        } else if(one == null || two == null) {
          return false;
        }else if(one.key != two.key) {
          return false;
        }
        return isTweakedIdentical(one.left, two.right) && isTweakedIdentical(one.right, two.left) || isTweakedIdentical(one.left, two.left) && isTweakedIdentical(one.right, two.right);
      }
    }
  • 相关阅读:
    JAVA理解逻辑程序的书上全部重要的习题
    体检套餐管理系统的综合版
    一路奔跑,一路寻找
    员工考勤信息管理小程序
    枚举的独特强大之处
    C#中HashTable的用法
    项目经理评分
    若想成功,请记住!
    数组的经典例子
    S1的小成果:MyKTV系统
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10253373.html
Copyright © 2011-2022 走看看