1. 程式人生 > >【LeetCode】101. Symmetric Tree 解題報告(Java & Python)

【LeetCode】101. Symmetric Tree 解題報告(Java & Python)

目錄

[LeetCode]

Total Accepted: 106639 Total Submissions: 313969 Difficulty: Easy

題目描述

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

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

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

But the following [1,2,2,null,3,null,3] is not:

    1
   / \
  2   2
   \   \
   3    3

Note:

  1. Bonus points if you could solve it both recursively and iteratively.

題目大意

判斷一棵二叉樹是不是映象二叉樹。

解題方法

DFS

參考了LeetCode官方解答,遞迴的方法實現比較左右子樹的左右子樹是否對稱。

不過確實可以提醒我一點,就是說,一個二叉樹遍歷的過程中不一定一定只有一個引數,也可以同時傳了兩個引數分別是左右好處是可以直接比較,當然這個時候需要把root放到兩個引數上進行比較。

本來也不是一個很難的題目,需要自己更多的掌握技巧,另外,不要把事情想複雜。

遞迴很重要的一部分是終止條件的確定。這個一定要認真的去寫。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isSymmetric(TreeNode root) {
        return isMirror(
root,root); } public boolean isMirror(TreeNode left,TreeNode right){ if(left == null && right == null) return true; if(left == null || right == null) return false; return (left.val == right.val) && isMirror(left.left,right.right) && isMirror(left.right,right.left); } }

AC:1ms

二刷的時候寫的Python解法如下:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if not root: return True
        return self.isMirror(root.left, root.right)
        
    def isMirror(self, left, right):
        if not left and not right: return True
        if not left or not right: return False
        return left.val == right.val and self.isMirror(left.left, right.right) and self.isMirror(left.right, right.left)

BFS

使用一個佇列和兩個節點的方式。

需要注意一個,就是當leftnull && rightnull的時候並不是和方法一一樣進行返回是 true,因為方法一是遞迴,遞迴的一個結束並不代表所有都結束,兩個都為空代表這兩個子樹是相同的,所以返回true.而迴圈需要把所有的節點都遍歷完才能確定返回結果,除非提前遇到不同的節點值而終止,所以是continue;

另外這個方法最後的return true就是對上面這個的補充,以為沒有提前終止一直到最後都比較了,所以說明是映象的。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isSymmetric(TreeNode root) {
        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);
        q.add(root);
        while(!q.isEmpty()){
            TreeNode left=q.poll();
            TreeNode right=q.poll();
            if(left==null && right==null)   continue;
            if(left==null || right==null)   return false;
            if(left.val != right.val)   return false;
            q.add(left.left);
            q.add(right.right);
            q.add(left.right);
            q.add(right.left);
        }
        return true;
    }
    
}

AC:3ms

而刷的時候的Python解法如下:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if not root: return True
        que = collections.deque()
        que.append(root.left)
        que.append(root.right)
        while que:
            left, right = que.popleft(), que.popleft()
            if not left and not right:
                continue
            if not left or not right:
                return False
            if left.val != right.val:
                return False
            que.append(left.left)
            que.append(right.right)
            que.append(left.right)
            que.append(right.left)
        return True

日期

2016 年 05月 8日
2018 年 11 月 19 日 —— 週一又開始了