二叉树如图所示:
2
/ \1 3
/ \ / \
1 2 6 5
反转后
结果如下:
2
/ \3 1
/ \ / \
5 6 2 1
程序如下:
public static TreeNode InvertTree(TreeNode root)
{
Queue<TreeNode> q = new Queue<TreeNode>();
if (root != null) q.Enqueue(root);
while (q.Count > 0)
{
TreeNode node = q.Dequeue();
TreeNode tmp = node.Left;
node.Left = node.Right;
node.Right = tmp;
if (node.Left != null)
{
q.Enqueue(node.Left);
}
if (node.Right != null)
{
q.Enqueue(node.Right);
}
}
return root;
}
递归版:
public static TreeNode InvertTree1(TreeNode root)
{
if (root == null) return root;
TreeNode tmp = root.Left;
root.Left = InvertTree1(root.Right);
root.Right = InvertTree(tmp);
return root;
}
1278

被折叠的 条评论
为什么被折叠?



