Invert a binary tree.
4
/ \
2 7
/ \ / \
1 3 6 9
to
4
/ \
7 2
/ \ / \
9 6 3 1
**反转二叉树
方法一**:引入一个队列进行层序遍历(leetcode时间超过20%的提交)
/**
* 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) {
if(root==null) return null;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
TreeNode node = queue.poll();
TreeNode left = node.left;
node.left = node.right;
node.right=left;
if(node.left != null) queue.offer(node.left);
if(node.right != null) queue.offer(node.right);
}
return root;
}
}
方法二:递归(leetcode时间超过100%的提交)
public class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) return null;
TreeNode left = root.left, right = root.right;
root.left = invertTree(right);
root.right = invertTree(left);
return root;
}
}