码迷,mamicode.com
首页 > 其他好文 > 详细

101. Symmetric Tree

时间:2018-07-19 13:46:55      阅读:145      评论:0      收藏:0      [点我收藏+]

标签: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. 

 

101. Symmetric Tree

标签:ati   link   bin   lse   ror   def   ISE   span   root   

原文地址:https://www.cnblogs.com/tobeabetterpig/p/9335087.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!