101. Symmetric Tree - Easy

前往題目

想法

  • 嘗試用了BFS但沒有成功,本來想說要用size來判斷然後分左右邊
  • 看了discussion才知道直接用leftright就好,跟DFS一樣

思路

DFS

  1. 每輪都比較leftright node的值
  2. 繼續用left的子樹還有right的子樹呼叫DFS

BFS解法

Code

class Solution {
    public boolean isSymmetric(TreeNode root) {
        return dfs(root.left, root.right);
    }

    private boolean dfs(TreeNode left, TreeNode right) {
        // Reach the end
        if (left == null && right == null) {
            return true;
        }
        // One of them reach the end but other one hasnt
        if (left == null || right == null) {
            return false;
        }

        // Check their values, check left and right sub node values
        return left.val == right.val &&
               dfs(left.left, right.right) &&
               dfs(left.right, right.left);
    }
}

2024/10/26

  • 這次想到的是BFS,也是蠻好寫的
class Solution {
    public boolean isSymmetric(TreeNode root) {
        Queue<TreeNode> q = new LinkedList();

        // Skip the root
        q.offer(root.left);
        q.offer(root.right);

        while (!q.isEmpty()) {
            int size = q.size();

            TreeNode left = q.poll();
            TreeNode right = q.poll();

            // Reached the leaf, skip it
            if (left == null && right == null)
                continue;
            // One of them is null, means not the same
            if (left == null || right == null)
                return false;
            if (left.val != right.val)
                return false;
            
            // Offer the following nodes
            q.offer(left.left);
            q.offer(right.right);
            
            q.offer(left.right);
            q.offer(right.left);
        }

        return true;
    }
}

101. Symmetric Tree - Easy
https://f88083.github.io/2024/01/14/101-Symmetric-Tree-Easy/
作者
Simon Lai
發布於
2024年1月14日
許可協議