Invert a binary tree.
DFS递归,依次交换左右节点
public class Solution {
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
public void invertBinaryTree(TreeNode root) {
if(root == null) return;
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
if(root.left != null) invertBinaryTree(root.left);
if(root.right != null) invertBinaryTree(root.right);
}
}
DFS非递归
public class Solution {
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
public void invertBinaryTree(TreeNode root) {
if(root == null) return;
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while(!stack.isEmpty()) {
TreeNode tmp = stack.pop();
TreeNode left = tmp.left;
tmp.left = tmp.right;
tmp.right = left;
if(tmp.right != null) stack.push(tmp.right);
if(tmp.left != null) stack.push(tmp.left);
}
}
}
public class Solution {
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
public void invertBinaryTree(TreeNode root) {
if(root == null) return;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
while(!queue.isEmpty()) {
TreeNode tmp = queue.poll();
TreeNode left = tmp.left;
tmp.left = tmp.right;
tmp.right = left;
if(tmp.right != null) queue.offer(tmp.right);
if(tmp.left != null) queue.offer(tmp.left);
}
}
}