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

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
    原文作者:ethannnli
    原文地址: https://segmentfault.com/a/1190000003757870
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞