LeetCode -- Invert Binary Tree

来源:互联网 发布:java中格式化 编辑:程序博客网 时间:2024/06/05 18:46
题目描述:
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;}}


1 0