我新建的个人博客,欢迎访问:hmilzy.github.io
226.翻转二叉树
题目链接:翻转二叉树
这道题又帮忙复习了一下二叉树的递归:前序、后序、中序
同时用层序遍历也可以
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
class Solution {
public TreeNode invertTree(TreeNode root) { if (root == null) { return null; } invertTree(root.left); invertTree(root.right); swapChildren(root); return root; }
private void swapChildren(TreeNode root) { TreeNode tmp = root.left; root.left = root.right; root.right = tmp; } }
|
101. 对称二叉树
题目链接:对称二叉树
值得思考,太强了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
|
class Solution {
public boolean isSymmetric(TreeNode root) { return compare(root.left, root.right); }
private boolean compare(TreeNode left, TreeNode right) {
if (left == null && right != null) { return false; } if (left != null && right == null) { return false; }
if (left == null && right == null) { return true; } if (left.val != right.val) { return false; } boolean compareOutside = compare(left.left, right.right); boolean compareInside = compare(left.right, right.left); return compareOutside && compareInside; }
public boolean isSymmetric2(TreeNode root) { Deque<TreeNode> deque = new LinkedList<>(); deque.offerFirst(root.left); deque.offerLast(root.right); while (!deque.isEmpty()) { TreeNode leftNode = deque.pollFirst(); TreeNode rightNode = deque.pollLast(); if (leftNode == null && rightNode == null) { continue; }
if (leftNode == null || rightNode == null || leftNode.val != rightNode.val) { return false; } deque.offerFirst(leftNode.left); deque.offerFirst(leftNode.right); deque.offerLast(rightNode.right); deque.offerLast(rightNode.left); } return true; }
public boolean isSymmetric3(TreeNode root) { Queue<TreeNode> deque = new LinkedList<>(); deque.offer(root.left); deque.offer(root.right); while (!deque.isEmpty()) { TreeNode leftNode = deque.poll(); TreeNode rightNode = deque.poll(); if (leftNode == null && rightNode == null) { continue; }
if (leftNode == null || rightNode == null || leftNode.val != rightNode.val) { return false; } deque.offer(leftNode.left); deque.offer(rightNode.right); deque.offer(leftNode.right); deque.offer(rightNode.left); } return true; }
}
|