[Leetcode] Same Tree Symmetric Tree 相同树 对称树

news/2024/7/2 21:03:32 标签: 数据结构与算法

Same Tree

Given two binary trees, write a function to check if they are equal or not.

Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

递归法

复杂度

时间 O(N) 空间 O(h) 递归栈空间

思路

如果两个根节点一个为空,一个不为空,或者两个根节点值不同,说明出现了不一样的地方,返回假。如果两个节点都是空,则是一样的,返回真。然后我们再递归它们的左右节点,如果递归结果中一个或两个是假,就返回假。否则,说明左右子树都是完全一样的。

代码

public class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if(p == null && q == null) return true;
        if(p == null || q == null || p.val != q.val) return false;
        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
}

2018/2

class Solution:
    def isSameTree(self, p, q):
        """
        :type p: TreeNode
        :type q: TreeNode
        :rtype: bool
        """
        if p is None and q is None:
            return True
        if p is None or q is None:
            return False
        return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

2018/10

func isSameTree(p *TreeNode, q *TreeNode) bool {
    if p == nil && q == nil {
        return true
    }
    if p != nil && q != nil {
        return p.Val == q.Val && isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right)
    }
    return false
}

Symmetric Tree

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree is symmetric:

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

But the following is not:

    1
   / \
  2   2
   \   \
   3    3

递归法

复杂度

时间 O(N) 空间 O(h) 递归栈空间

思路

其实和Same Tree写法是一样的,Same Tree是比较两个节点的两个左边,然后再比较两个节点的两个右边。而对称树是要判断左节点的左节点和右节点的右节点相同(外侧),左节点的右节点和右节点的左节点相同(内侧)。不过对称树是判断一棵树,我们要用Same Tree一样的写法,就要另写一个可以比较两个节点的函数。

注意,Leetcode中当根节点为空时,树也是对称的

代码

    public class Solution {
        public boolean isSymmetric(TreeNode root) {
            return root == null ? true : helper(root.left, root.right);
        }
        
        private boolean helper(TreeNode node1, TreeNode node2){
            if(node1 == null && node2 == null){
                return true;
            }
            if(node1 == null || node2 == null || node1.val != node2.val){
                return false;
            }
            return helper(node1.left, node2.right) && helper(node1.right, node2.left);
        }
    }

2018/2

class Solution:
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        return root is None or self.helper(root.left, root.right)
        
    def helper(self, node1, node2):
        if node1 is None and node2 is None:
            return True
        if node1 is None or node2 is None:
            return False
        return node1.val == node2.val and self.helper(node1.right, node2.left) and self.helper(node1.left, node2.right)

迭代法

复杂度

时间 O(N) 空间 O(h)

思路

因为该题本质就是二叉树遍历,所以我们也可以用迭代来解。这里用一个队列,两棵树按照对称的顺序加入节点,然后进行比较。

代码

public class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root == null) return true;
        Queue<TreeNode> queue1 = new LinkedList<TreeNode>();
        Queue<TreeNode> queue2 = new LinkedList<TreeNode>();
        queue1.offer(root.left);
        queue2.offer(root.right);
        while(!queue1.isEmpty() && !queue2.isEmpty()){
            TreeNode node1 = queue1.poll();
            TreeNode node2 = queue2.poll();
            // 如果都是null,说明是相同的
            if(node1 == null && node2 == null){
                continue;
            }
            // 如果有一个是null,或者值不同,则有问题
            if(node1 == null || node2 == null || node1.val != node2.val){
                return false;
            }
            queue1.offer(node1.left);
            queue2.offer(node2.right);
            queue1.offer(node1.right);
            queue2.offer(node2.left);
        }
        return queue1.isEmpty() && queue2.isEmpty();
    }
}

2018/2

from collections import deque

class Solution:
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if root is None:
            return True
        queue1 = deque()
        queue2 = deque()
        queue1.append(root.left)
        queue2.append(root.right)
        while queue1 and queue2:
            node1 = queue1.popleft()
            node2 = queue2.popleft()
            if node1 is None and node2 is None:
                continue
            if node1 is None or node2 is None:
                return False
            if node1.val != node2.val:
                return False
            queue1.append(node1.left)
            queue2.append(node2.right)
            queue1.append(node1.right)
            queue2.append(node2.left)
        return True

http://www.niftyadmin.cn/n/1000288.html

相关文章

maven私有仓库

参考&#xff1a;http://blog.csdn.net/mtkong/article/details/9377527转载于:https://www.cnblogs.com/tintindeng/p/4819490.html

关于app transfer之后的开发

原文 http://blog.csdn.net/donghong2008/article/details/38020855 网络上有很多开发者提问怎么转让App并想知道具体的流程。实际上Appstore的App转让流程还是比较简单的&#xff0c;下面特酷吧根据自己的实际操作总结下iOS Appstore中App的转让流程&#xff0c;供大家参考。…

Android软件开发之获取通讯录联系人信息(二十九)

Android软件开发之获取通讯录联系人信息雨松MOMO原创文章如转载&#xff0c;请注明&#xff1a;转载自雨松MOMO的博客原文地址:http://blog.csdn.net/xys289187120/article/details/6730957Android手机的通讯录联系人全部都存在系统的数据库中&#xff0c;如果须要获得通讯里联…

一个关于Linux Bridge配置的吐嘈

分享一下我老师大神的人工智能教程&#xff01;零基础&#xff0c;通俗易懂&#xff01;http://blog.csdn.net/jiangjunshow也欢迎大家转载本篇文章。分享知识&#xff0c;造福人民&#xff0c;实现我们中华民族伟大复兴&#xff01;话说有些事情十分适合在放假前的一天折腾一天…

Word和WPS插件开发总结

为了实现办公的自动化&#xff0c;需要实现文档的自动流转。开发出的WORD和WPS插件的功能包括显示批注、隐藏批注、引入文件、附加对象、保存文档、退出应用。 1 Word插件开发 1.1 插件开发方法 1.1.1 开发语言 开发语言的选择&#xff0c;可以选择C和C#。 1.1.2 Visual studio…

馋-c语言的规则

在记者采访过程&#xff0c;有着c的认识的情况&#xff0c;有时会被问到有关字符搭配以及运算先后顺序的问题&#xff0c;比方ab的值。iiii的值等类似的&#xff0c;这都属于c的符号方面的问题。那么如何才干轻而易举的去认识它呢&#xff1f; c语言有这种一个规则&#xff1a;…

Android AppWidget组件

res/xml/example_appwidget_info.xml 定义了AppWidget必要属性 <?xml version"1.0" encoding"utf-8"?> <appwidget-provider xmlns:android"http://schemas.android.com/apk/res/android" android:minWidth"160dp" android…

让人很容易误解的TCP拥塞控制算法

分享一下我老师大神的人工智能教程&#xff01;零基础&#xff0c;通俗易懂&#xff01;http://blog.csdn.net/jiangjunshow也欢迎大家转载本篇文章。分享知识&#xff0c;造福人民&#xff0c;实现我们中华民族伟大复兴&#xff01;正文很多人会认为一个好的TCP拥塞控制算法会…