【两次过】Lintcode 470. 扭转后等价的二叉树

本文介绍了一种算法,用于判断两棵二叉树是否可以通过若干次扭转操作达到等价状态。通过递归比较节点值和子树结构,确保两棵树在结构和节点值上完全一致。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

检查两棵二叉树是否在经过若干次扭转后可以等价。扭转的定义是,交换任意节点的左右子树。等价的定义是,两棵二叉树必须为相同的结构,并且对应位置上的节点的值要相等。

样例

例1:

输入:{1,2,3,4},{1,3,2,#,#,#,4}
输出:true
说明:
        1             1
       / \           / \
      2   3    和   3   2
     /                   \
    4                     4

是相同的。

例2:

输入:{1,2,3,4},{1,3,2,4}
输出:false
说明:

        1             1
       / \           / \
      2   3    和   3   2
     /             /
    4             4

不一样。

挑战

在 O(n) 的时间内完成。

注意事项

你可以假设二叉树中不会有重复的节点值。


解题思路:

判断值相等
取到 a的左右两边 取到b的左右二边

a的左边 必须等于b的右边 或者 等于左边
a的右边 必须等于b的左边 或者 等于右边
只有满足一种条件就是ok的
这样才是identical

/**
 * 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) {
        // write your code here
        if(a == null && b == null)
            return true;
        if(a == null || b == null)
            return false;
        if(a.val != b.val)
            return false;
        
        return (isTweakedIdentical(a.left, b.left) && isTweakedIdentical(a.right, b.right)) || (isTweakedIdentical(a.left, b.right) && isTweakedIdentical(a.right, b.left));
    }
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值