[Leetcode]226. Invert Binary Tree

Invert a binary tree.

     4
   /   
  2     7
 /    / 
1   3 6   9

to

     4
   /   
  7     2
 /    / 
9   6 3   1

思路:这道题考的是树的遍历,先序和后序遍历都行,唯独中序遍历不行。eg:如上图,如果用中序遍历
   递归返回到 2 这个节点的时候,2 的左右已经互换,即 2.left.val = 3,2.right.val =1
   然后返回到4这个节点,接着 2,7互换。继续递归 4 的右边,此时 7 变为左节点,然而 6,7
   还未互换,而递归右边时,又把2 的左右互换了回来。
 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 class Solution {
11     public TreeNode invertTree(TreeNode root) {
12         if (root==null)
13             return null;
14         else {
15             TreeNode tmp = root.left;                        //先序,先交换左右,再递归
16             root.left = root.right;
17             root.right = tmp;
18             root.left = invertTree(root.left);
19             root.right = invertTree(root.right);
20         }
21         return root;
22     }
23 }
View Code
原文地址:https://www.cnblogs.com/David-Lin/p/7708521.html