标签:ati link bin lse ror def ISE span root
For example, this binary tree [1,2,2,3,4,4,3] is symmetric: 1 / 2 2 / \ / 3 4 4 3 But the following [1,2,2,null,3,null,3] is not:? 1 / 2 2 \ 3 3 /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public boolean isSymmetric(TreeNode root) { if(root == null){ return true; } TreeNode left = root.left; TreeNode right = root.right; return helper(left, right); } private boolean helper(TreeNode left, TreeNode right){ if(left == null && right == null){ return true; }else if( left == null || right == null){ return false; }else{ if( left.val != right.val){ return false; }else{ return helper(left.right, right.left) && helper(left.left, right.right); } } } } // iterative /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public boolean isSymmetric(TreeNode root) { Queue<TreeNode> queue = new LinkedList<>(); if(root == null){ return true; } queue.offer(root.left); queue.offer(root.right); while(!queue.isEmpty()){ TreeNode left = queue.poll(); TreeNode right = queue.poll(); if(left == null && right == null) continue; // continue instead of true, because there are more nodes in the queue waiting to be checked else if(left == null || right == null || left.val != right.val) return false; else{ queue.offer(left.left); queue.offer(right.right); queue.offer(left.right); queue.offer(right.left); } } return true; } } // add and poll can be used together with no problem??? // cant use ArrayDeque to implement this queue , otherwise error? why. Because in arraydeque, when you add or offer an null into the queue. It gives you NPE. In linked list its okay to add or offer null.
标签:ati link bin lse ror def ISE span root
原文地址:https://www.cnblogs.com/tobeabetterpig/p/9335087.html