题解 | #对称的二叉树#

对称的二叉树

https://www.nowcoder.com/practice/ff05d44dfdb04e1d83bdbdab320efbcb

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param pRoot TreeNode类
     * @return bool布尔型
     */
    public boolean isSymmetrical (TreeNode pRoot) {
        if (pRoot == null) {
            return true;
        }
        if (pRoot.left == null && pRoot.right != null ||
                pRoot.left != null && pRoot.right == null) {
            return false;
        }
        if (pRoot.left == null && pRoot.right == null) {
            return true;
        }
        if (pRoot.left.val != pRoot.right.val) {
            return false;
        }
        List<Integer> left = new ArrayList<>();
        List<Integer> right = new ArrayList<>();
        addLeft(pRoot.left, left);
        addRight(pRoot.right, right);

        if (left.size() != right.size()) {
            return false;
        }
        for (int i = 0; i < left.size(); i ++) {
            if (left.get(i) != right.get(i)) {
                return false;
            }
        }
        return true;
    }

    public void addLeft(TreeNode root, List<Integer> list) {
        if (root == null) {
            list.add(null);
            return;
        }
        list.add(root.val);
        addLeft(root.left, list);
        addLeft(root.right, list);
    }

    public void addRight(TreeNode root, List<Integer> list) {
        if (root == null) {
            list.add(null);
            return;
        }
        list.add(root.val);
        addRight(root.right, list);
        addRight(root.left, list);
    }
}

全部评论

相关推荐

MScoding:你这个实习有一个是当辅导老师,这个和找技术岗没有关系吧?
点赞 评论 收藏
分享
牛客765689665号:没有实习是硬伤,央国企看学历
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务