https://leetcode-cn.com/problems/invert-binary-tree/submissions/ 递归法:
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root == null) return root;
TreeNode left = invertTree(root.left);
TreeNode right = invertTree(root.right);
root.left = right;
root.right = left;
return root;
}
}
层序遍历法:
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root == null) return null;
Queue<TreeNode> que = new LinkedList();
que.offer(root);
while(!que.isEmpty()){
TreeNode poll = que.poll();
TreeNode temp = poll.right;
poll.right = poll.left;
poll.left = temp;
if(poll.left != null){
que.offer(poll.left);
}
if(poll.right != null){
que.offer(poll.right);
}
}
return root;
}
}
|