Invert a binary tree.
4 / \ 2 7 / \ / \ 1 3 6 9to
4 / \ 7 2 / \ / \ 9 6 3 1Trivia:
This problem was inspired by this original tweet by Max Howell:
求一颗二叉树的镜像过程:
先前序遍历这棵树的每个结点,如果遍历到的结点有子结点,就交换它的子结点。当交换完所有非叶子结点的左右子结点之后,就得到了树的镜像。下面是例子中的转换过程;
此题解法一:用递归来转换每个结点的左右子结点,代码如下
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
invertTree(root.left);
invertTree(root.right);
return root;
}
}
此题解法二:用队列保存每个结点,循环来转换每个结点的左右子结点,代码如下:
public TreeNode invertTree(TreeNode root) {
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
if(root!=null){
queue.add(root);
}
while(!queue.isEmpty()){
TreeNode p = queue.poll();
if(p.left!=null)
queue.add(p.left);
if(p.right!=null)
queue.add(p.right);
TreeNode temp = p.left;
p.left = p.right;
p.right = temp;
}
return root;
}