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;
            }
        }
    }
  • 相关阅读:
    排序——快速排序
    文件操作(获取英文单词)
    两位整数变英文单词
    Doodle Poll 投票文档
    手机与笔记本蓝牙配对
    浏览器的断电续传功能
    3ds max 2011 安装步骤及其注意事项
    anti-alising的基本理解
    OpenGL pipeline (very important)
    secureCrt
  • 原文地址:https://www.cnblogs.com/Jessiezyr/p/10675683.html
Copyright © 2011-2022 走看看