首页 > 代码库 > LeetCode 226 Invert Binary Tree

LeetCode 226 Invert Binary Tree

Invert a binary tree.

     4   /     2     7 / \   / 1   3 6   9

to

     4   /     7     2 / \   / 9   6 3   1

 

思路:

递归地交换根节点的左右子树即可。

 

解法:

 1 /* 2     public class TreeNode 3     { 4         int val; 5         TreeNode left; 6         TreeNode right; 7  8         TreeNode(int x) 9         { val = x; }10     }11 */12 13 public class Solution14 {15     public TreeNode invertTree(TreeNode root)16     {17         if(root == null)18             return null;19 20         TreeNode temp = root.left;21         root.left = root.right;22         root.right = temp;23 24         invertTree(root.left);25         invertTree(root.right);26 27         return root;28     }29 }

 

LeetCode 226 Invert Binary Tree