样例
1 1
/ \ / \
2 3 => 3 2
/ \
4 4
通常使用递归的办法
public class Solution {
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
public void invertBinaryTree(TreeNode root) {
// write your code here
TreeNode index=root;
if(index!=null){
TreeNode temp=index.left;
index.left=root.right;
index.right=temp;
invertBinaryTree(index.left);
invertBinaryTree(index.right);
}
}
}
不递归则用栈保存所有节点
public void invertBinaryTree(TreeNode root) {
Stack<TreeNode> stack=new Stack<TreeNode>();
TreeNode index=root;
stack.push(root);
while(stack.size()>0&& index!=null){
index=stack.pop();
if(index!=null && (index.right!=null || index.left!=null)){
swap(index);
}
if(index.left!=null){
stack.push(index.left);
}
if(index.right!=null){
stack.push(index.right);
}
}
}
public void swap(TreeNode index){
if(index!=null && (index.left!=null || index.right!=null)){
TreeNode tmp=index.left;
index.left=index.right;
index.right=tmp;
}
}