【LeetCode】Symmetric Tree
发布时间:2020-12-14 05:06:46 所属栏目:大数据 来源:网络整理
导读:【Description】 Given a binary tree,check whether it is a mirror of itself (ie,symmetric around its center). For example,this binary tree? [1,2,3,4,3] ?is symmetric: 1 / 2 2 / / 3 4 4 3 ? But the following? [1,null,3] ?is not: 1 / 2 2
【Description】 Given a binary tree,check whether it is a mirror of itself (ie,symmetric around its center). For example,this binary tree? 1 / 2 2 / / 3 4 4 3 ? But the following? 1 / 2 2 3 3 ? Note: ? 【AC code】 Reference:?https://leetcode.com/articles/symmetric-tree/ 一、递归 时间复杂度:O(n) 1 class Solution { 2 public boolean isSymmetric(TreeNode root) { 3 if (root == null) return true; 4 return isSymmetric(root.left,root.right); 5 } 6 private boolean isSymmetric(TreeNode r1,TreeNode r2) { 7 if (r1 == null && r2 == null) return true; 8 if ((r1 == null || r2 == null) || r1.val != r2.val) return false; 9 return isSymmetric(r1.left,r2.right) && isSymmetric(r1.right,r2.left); 10 } 11 } 二、迭代 时间复杂度:O(n) 1 class Solution { 2 public boolean isSymmetric(TreeNode root) { 3 Queue<TreeNode> q = new LinkedList<>(); 4 q.add(root); 5 q.add(root); 6 while (!q.isEmpty()) { 7 TreeNode t1 = q.poll(); 8 TreeNode t2 = q.poll(); 9 if (t1 == null && t2 == null) continue; 10 if (t1 == null || t2 == null) return false; 11 if (t1.val != t2.val) return false; 12 q.add(t1.left); 13 q.add(t2.right); 14 q.add(t1.right); 15 q.add(t2.left); 16 } 17 return true; 18 } 19 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |