• 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;
            }
        }
    }
  • 相关阅读:
    再谈反射
    XmlElement和XmlNode的区别
    几个常用的集合类的使用
    node.js 练习3 调用函数
    ioc 的好文章 转自 GavinJun
    sqlserver 使用小技巧总结
    node.js 练习2 (调用函数)
    c# 面向对象基础
    linq 和 lmabda 表达式 的用法 和优劣 转自 农码一生
    memcache 基本操作
  • 原文地址:https://www.cnblogs.com/Jessiezyr/p/10675683.html
Copyright © 2020-2023  润新知