[LeetCode] #101 Symmetric Tree 解題

題目連結

題型解說

這是一題難度為簡單的題目

需要設計一個方法,此方法會傳入一個二元樹 root

回傳這棵樹是不是左右對稱的

解題思路

這題跟上一題 [LeetCode] #100 Same Tree 解題 是高度相像的

唯一的差異是因為要確認是否對稱,所以是左邊跟右邊比,右邊跟左邊比,中間一樣跟中間比

其中一個沒比對上就回傳 false

程式碼

Java

class Solution {
    public boolean isSymmetric(TreeNode root) {
        if (root == null) {
            return true;
        }
        
        return isSymmetric(root.left, root.right);
    }
    
    public boolean isSymmetric(TreeNode p, TreeNode q) {
        if (p == null && q == null) {
            return true;
        } else if (p == null || q == null || p.val != q.val) {
            return false;
        }
        
        return isSymmetric(p.left, q.right) && isSymmetric(p.right, q.left);
    }
}
class Solution {
    public boolean isSymmetric(TreeNode root) {
        if (root == null) {
            return true;
        }
        
        Stack stack = new Stack();
        
        stack.push(root.left);
        stack.push(root.right);
        
        TreeNode temp1;
        TreeNode temp2;
        
        while (!stack.empty()) {
            temp1 = (TreeNode)stack.pop();
            temp2 = (TreeNode)stack.pop();
            
            if (temp1 == null && temp2 == null) {
                continue;
            } else if (temp1 == null || temp2 == null || temp1.val != temp2.val) {
                return false;
            }

            stack.push(temp1.right);
            stack.push(temp2.left);
            stack.push(temp1.left);
            stack.push(temp2.right);
        }
        
        return true;
    }
}