|
| 1 | +101_(对称二叉树)Symmetric Tree |
| 2 | +给定一个二叉树,检查它是否是镜像对称的。 |
| 3 | + |
| 4 | +输入: |
| 5 | +TreeNode* root:二叉树的根节点指针 |
| 6 | +输出: |
| 7 | +bool:是否是对称二叉树 |
| 8 | + |
| 9 | +输入: 给定二叉树: [1,2,2,3,4,4,3] , |
| 10 | + 1 |
| 11 | + / \ |
| 12 | + 2 2 |
| 13 | + / \ / \ |
| 14 | +3 4 4 3 |
| 15 | +输出: true |
| 16 | + |
| 17 | +solution1 |
| 18 | + |
| 19 | +判断是否是镜像对称,重要的就是判断对应位置的2个结点的值是否相等。用双端队列来实现 |
| 20 | + |
| 21 | +public boolean isSymmetric(TreeNode root){ |
| 22 | + if(root == null){ |
| 23 | + return true; |
| 24 | + } |
| 25 | + //队列做遍历 |
| 26 | + Deque<TreeNode> deque = new LinkedList<TreeNode>(); |
| 27 | + //根节点不用判断,直接加入左右孩子结点 |
| 28 | + deque.addFirst(root.left); |
| 29 | + deque.addLast(root.right); |
| 30 | + |
| 31 | + TreeNode preNode = null; |
| 32 | + TreeNode postNode = null; |
| 33 | + |
| 34 | + while(!deque.isEmpty()){ |
| 35 | + //取出列队两个元素 |
| 36 | + preNode = deque.pollFirst(); |
| 37 | + postNode = deque.pollLast(); |
| 38 | + //如果当前结点是空结点,结束本次循环,即不需要检查后续结点 |
| 39 | + if(preNode == null && postNode == null){ |
| 40 | + continue; |
| 41 | + } |
| 42 | + //如果不对称返回false, |
| 43 | + if(preNode == null || postNode == null){ |
| 44 | + return false; |
| 45 | + } |
| 46 | + if(preNode.val != postNode.val){ |
| 47 | + return false; |
| 48 | + } else{ |
| 49 | + deque.addFirst(preNode.right);//preNode右孩子入队 |
| 50 | + deque.addFirst(preNode.left);//preNode左孩子入队 |
| 51 | + |
| 52 | + deque.addLast(postNode.left);//postNode左孩子入队 |
| 53 | + deque.addLast(postNode.right);//postNode右孩子入队 |
| 54 | + } |
| 55 | + } |
| 56 | + return true;//都是对称的返回真 |
| 57 | + } |
| 58 | + |
| 59 | + |
| 60 | +solution2 |
| 61 | + public boolean isSysmmetric2(TreeNode root){ |
| 62 | + if(root == null){ |
| 63 | + return true; |
| 64 | + } |
| 65 | + return checkNodes(root.left,root.right); |
| 66 | + } |
| 67 | + |
| 68 | + public boolean checkNodes(TreeNode node1,TreeNode node2){ |
| 69 | + if(node1 == null && node2 == null){ |
| 70 | + return true; |
| 71 | + } |
| 72 | + if(node1 == null || node2 == null){ |
| 73 | + return false; |
| 74 | + } |
| 75 | + if(node1.val != node2.val){ |
| 76 | + return false; |
| 77 | + } else{ |
| 78 | + return checkNodes(node1.left,node2.right) && checkNodes(node1.right,node2.left); |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + |
| 83 | + |
| 84 | + |
| 85 | + |
| 86 | + |
| 87 | + |
| 88 | + |
| 89 | + |
| 90 | + |
| 91 | + |
| 92 | + |
| 93 | + |
| 94 | + |
| 95 | + |
| 96 | + |
0 commit comments