101. Symmetric Tree
Leetcode Tree Depth-first Search Breadth-first SearchGiven 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]
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
Note: * Bonus points if you could solve it both recursively and iteratively.
分析¶
二叉树对称,iff, 左子树和右子树对称。 那么怎么判断两棵树对称?
两棵树对成,iff
- 左节点和右节点的值相等
- 两棵树的左子树和右子树依次对称
public boolean isSymmetricSubTree(TreeNode root) {
if (root == null) return true;
return isSymmetricNodes(root.left, root.right);
}
private boolean isSymmetricSubTree(TreeNode root1, TreeNode root2) {
if (root1 == null || root2 == null) return root1 == root2;
return root1.val == root2.val &&
isSymmetricSubTree(root1.left, root2.right) &&
isSymmetricSubTree(root1.right, root2.left);
}
isSymmetricSubTree
还可以再优化一点, 也就是将根节点看成是子节点,相当于增加了一个虚拟根节点。
public boolean isSymmetricSubTree(TreeNode root) {
return isSymmetricNodes(root, root);
}
同样的思路,使用迭代:
public boolean isSymmetric(TreeNode root) {
if (root == null) return true;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
stack.push(root);
while (!stack.isEmpty()) {
TreeNode left = stack.pop();
TreeNode right = stack.pop();
if (left.val != right.val) return false;
if (left.left != null && right.right != null) {
stack.push(left.left); stack.push(right.right);
} else if (left.left != right.right) return false;
if (left.right != null && right.left != null) {
stack.push(left.right); stack.push(right.left);
} else if (left.right != right.left) return false;
}
return true;
}
发现使用BFS思路的QUEUE,使用迭代可以简化一些:
public boolean isSymmetric(TreeNode root) {
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
q.add(root);
while (!q.isEmpty()) {
TreeNode t1 = q.poll();
TreeNode t2 = q.poll();
if (t1 == null && t2 == null) continue;
if (t1 == null || t2 == null) return false;
if (t1.val != t2.val) return false;
q.add(t1.left);
q.add(t2.right);
q.add(t1.right);
q.add(t2.left);
}
return true;
}