zoukankan      html  css  js  c++  java
  • Lintcode470-Tweaked Identical Binary Tree-Easy

    470. Tweaked Identical Binary Tree

    Check two given binary trees are identical or not. Assuming any number of tweaksare allowed. A tweak is defined as a swap of the children of one node in the tree.

    Example

    Example 1:

    Input:{1,2,3,4},{1,3,2,#,#,#,4}
    Output:true
    Explanation:
            1             1
           /            / 
          2   3   and   3   2
         /                   
        4                     4
    
    are identical.
    

    Example 2:

    Input:{1,2,3,4},{1,3,2,4} 
    Output:false
    Explanation:
    
            1             1
           /            / 
          2   3   and   3   2
         /             /
        4             4
    
    are not identical.
    

    Challenge

    O(n) time

    Notice

    There is no two nodes with the same value in the tree.

    思路:

    tweaked identical tree 有两种情况,一种是b树是a树的tweak树(每个对应结点都交换),二是b树和a树完全相同。这两种情况为true。

    思路和Lintcode469 Same tree相似,只是多一种组合。

    代码:

    /**
     * Definition of TreeNode:
     * public class TreeNode {
     *     public int val;
     *     public TreeNode left, right;
     *     public TreeNode(int val) {
     *         this.val = val;
     *         this.left = this.right = null;
     *     }
     * }
     */
    
    public class Solution {
        /**
         * @param a: the root of binary tree a.
         * @param b: the root of binary tree b.
         * @return: true if they are tweaked identical, or false.
         */
        public boolean isTweakedIdentical(TreeNode a, TreeNode b) {
            if (a == null && b == null) {
                return true;
            }
            else if (a != null && b != null) {
                return (a.val == b.val && isTweakedIdentical(a.left, b.left) 
                        && isTweakedIdentical(a.right, b.right))
                        ||(a.val == b.val && isTweakedIdentical(a.left, b.right) 
                        && isTweakedIdentical(a.right, b.left));
            }
            else {
                return false;
            }
        }
    }
  • 相关阅读:
    postfix遇到的问题
    SElinux以及防火墙的关闭
    centos查看系统信息
    WINDOWS访问SAMBA提示没有权限
    常用命令
    口才
    【李敖的管理经】
    随笔
    查询MX记录
    bash: ifconfig: command not found
  • 原文地址:https://www.cnblogs.com/Jessiezyr/p/10675683.html
Copyright © 2011-2022 走看看