题目:Invert Binary Tree
描述:
invert binary tree:
4
/ \
2 7
/ \ / \
1 3 6 9
to
4
/ \
7 2
/ \ / \
9 6 3 1
翻译:将二叉树的左边和右边进行置换
答案:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null)
return root;
TreeNode node = root.left;
root.left = root.right;
root.right = node;
invertTree(root.left);
invertTree(root.right);
return root;
}
}
算法解释
运用二叉树的广度遍历,将每个节点的左子节点和右子节点调换