두 갈래 나무, 거울 자바 구현 여부 판단

1892 단어 LeetCode
비귀속 방법, 대기열 사용:
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.*;
public class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root==null)
            return true;
        Queue queue=new LinkedList();
        queue.add(root);
        queue.add(root);
        return issymmetric(queue);
    }
    public boolean issymmetric(Queue queue){
        while(!queue.isEmpty()){
            TreeNode temp1=queue.poll();
            TreeNode temp2=queue.poll();
            if(temp1==null&&temp2==null){
                continue;
            }
            else if(temp1==null||temp2==null){
                return false;
            }
            else if(temp1.val!=temp2.val){
                return false;
            }
            queue.add(temp1.left);
            queue.add(temp2.right);
            queue.add(temp1.right);
            queue.add(temp2.left);
        }
        return true;
    }
}

귀속 방법:
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root==null)
            return true;
        return issymmetric(root.left,root.right);
    }
    public boolean issymmetric(TreeNode root1,TreeNode root2){
        if(root1==null&&root2==null)
            return true;
        if(root1==null||root2==null)
            return false;
        if(root1.val!=root2.val)
            return false;
        return issymmetric(root1.left,root2.right)&&issymmetric(root1.right,root2.left);
    }
}

좋은 웹페이지 즐겨찾기