코린이의 소소한 공부노트

[LeetCode/Easy] 101. Symmetric Tree 본문

코딩테스트 풀이/JAVA

[LeetCode/Easy] 101. Symmetric Tree

무지맘 2023. 7. 17. 19:40

1. Input

1) TreeNode root

 

2. Output

1) root가 좌우대칭 트리라면 true, 아니면 false를 반환

 

3. Constraint

1) 노드 수의 범위는 [1, 1000]이다.

2) -100 <= Node.val <= 100

 

4. Example

Input: root = [1,2,2,3,4,4,3] -> Output: true

Input: root = [1,2,2,null,3,null,3] -> Output: false

 

5. Code

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root.left==null){
            if(root.right==null) return true;
            else return false;
        } else if(root.right==null) return false;
        else{
            Stack<TreeNode> ls = new Stack<>();
            Stack<TreeNode> rs = new Stack<>();
            ls.push(root.left); rs.push(root.right);
            while(!ls.empty() && !rs.empty()){
                TreeNode ln = ls.pop();
                TreeNode rn = rs.pop();
                if(ln==null){
                    if(rn==null) continue;
                    else return false;
                } else if(rn==null) return false;
                if(ln.val!=rn.val) return false;
                ls.push(ln.left); ls.push(ln.right);
                rs.push(rn.right); rs.push(rn.left);
            }
            if(ls.size()==0 && rs.size()==0) return true;
            else return false;
        }
    }
}

- 13%, 61%