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);
      }
    }
  • 相关阅读:
    STM32的串口DMA收发以及双缓冲区的实现
    平衡二叉树
    二叉树的深度
    3D数学基础(四)四元数和欧拉角
    3D数学基础(三)矩阵
    3D数学基础(二)向量
    3D数学基础(一)Unity坐标系
    快速学会开发微信小程序
    苦逼的程序员
    开通博客,在这个年末,重新开始。
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10253373.html
Copyright © 2011-2022 走看看