题目:
翻转一棵二叉树
1 1
/ \ / \
2 3 => 3 2
/ \
4 4
将root的左右子树的值交换,并递归遍历&交换root的左右子树。
代码:
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/*
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
public void invertBinaryTree(TreeNode root) {
// write your code here
if(root!=null)
{
TreeNode temp=new TreeNode(0);
temp=root.left;
root.left=root.right;
root.right=temp;
invertBinaryTree(root.left);
invertBinaryTree(root.right);
}
}
}