Invert a binary tree.
Example:
Input:
4 / \ 2 7 / \ / \ 1 3 6 9
Output:
4 / \ 7 2 / \ / \ 9 6 3 1
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
Queue<TreeNode> q = new LinkedList();
if(root != null) q.offer(root);
while(!q.isEmpty()){
TreeNode p = q.poll();
TreeNode tmp = p.left;
p.left = p.right;
p.right = tmp;
if(p.left != null) q.offer(p.left);
if(p.right != null) q.offer(p.right);
}
return root;
}
}
class Solution {
public TreeNode invertTree(TreeNode root) {
// Queue<TreeNode> q = new LinkedList();
// if(root != null) q.offer(root);
// while(!q.isEmpty()){
// TreeNode p = q.poll();
// TreeNode tmp = p.left;
// p.left = p.right;
// p.right = tmp;
// if(p.left != null) q.offer(p.left);
// if(p.right != null) q.offer(p.right);
// }
// return root;
if(root == null) return null;
TreeNode tmp = root.left;
root.left = invertTree(root.right);
root.right = invertTree(tmp);
return root;
}
}
或者更简单的递归,看起来好几把弱智,其实包含了很深的科学道理