您的位置:首页 > 其它

LeetCode -- Invert Binary Tree

2015-10-30 23:24 323 查看
题目描述:
Invert a 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 {
*     public int val;
*     public TreeNode left;
*     public TreeNode right;
*     public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode InvertTree(TreeNode root)
{

Travel(ref root);
return root;
}

private void Travel(ref TreeNode current)
{
if(current == null || current.left == null && current.right == null){
return;
}

Travel(ref current.left);
Travel(ref current.right);
Swap(ref current);
}

private void Swap(ref TreeNode n)
{
var tmp = n.left;
n.left = n.right;
n.right = tmp;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: