LeetCode 热题100-40-对称二叉树

核心思想:递归/迭代
思路:
将一棵树划分为两半,每次移动,同时指向同一个位置的元素,遍历即可
递归版本:

/**
 * 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) {
        return for_fun(root,root);
    }

    public boolean for_fun(TreeNode left,TreeNode right){
        if(left == null && right != null){
            return false;
        }else if(left != null && right == null){
            return false;
        }else if(left == null && right == null){
            return true;
        }else if(left.val != right.val){
            return false;
        }
        return for_fun(left.left,right.right) && for_fun(left.right,right.left);
    }
}

LeetCode最佳答案:

class Solution {
    public boolean isSymmetric(TreeNode root) {
        return check(root, root);
    }

    public boolean check(TreeNode p, TreeNode q) {
        if (p == null && q == null) {
            return true;
        }
        if (p == null || q == null) {
            return false;
        }
        return p.val == q.val && check(p.left, q.right) && check(p.right, q.left);
    }
}

迭代版本:

class Solution {
    public boolean isSymmetric(TreeNode root) {
        return for_fun(root,root);
    }

    public boolean for_fun(TreeNode left,TreeNode right){
    	//这里别用ArrayDeque,因为这个不然插入null值,LinkedList可以插入
        Deque<TreeNode> deque = new LinkedList<>();
        deque.addLast(left);
        deque.addLast(right);
        while(left != null || right != null || !deque.isEmpty()){
            left = deque.pollLast();
            right = deque.pollLast();
            if(left == null && right == null){
                continue;
            }
            if(left == null || right == null){
                return false;
            }
            if(left.val != right.val){
                return false;
            }
            deque.addLast(left.left);
            deque.addLast(right.right);

            deque.addLast(left.right);
            deque.addLast(right.left);
        }
        return true;
    }
}

你可能感兴趣的:(Leetcode热题100,leetcode,java)