/**
 * 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) {
        if (root == null || (root.left == null && root.right == null)) return root;

            TreeNode left = root.left;
            root.left = InvertTree(root.right);
            root.right = InvertTree(left);
            return root;
    }
}

https://leetcode.com/problems/invert-binary-tree/#/description

 

补充一个使用层次遍历处理的方案,java实现

 1 class Solution {
 2     public TreeNode invertTree(TreeNode root) {
 3         List<TreeNode> nodes = new LinkedList<>();
 4         if (root != null) {
 5             nodes.add(root);
 6         }
 7         while (!nodes.isEmpty()) {
 8             int numNodes = nodes.size();
 9             while (numNodes > 0) {
10                 TreeNode node = nodes.remove(0);
11                 // push children to the next layer by appending to the end of the list
12                 if (node.left != null) {
13                     nodes.add(node.left);
14                 }
15                 if (node.right != null) {
16                     nodes.add(node.right);
17                 }
18                 // flip
19                 TreeNode left = node.left;
20                 node.left = node.right;
21                 node.right = left;
22                 numNodes--;
23             }
24         }
25         return root;
26     }
27 }

 

补充一个python的实现:

1 class Solution:
2     def invertTree(self, root: TreeNode) -> TreeNode:
3         if root == None:
4             return None
5         left = root.left
6         root.left = self.invertTree(root.right)
7         root.right = self.invertTree(left)
8         return root

 

posted on 2017-04-19 11:02  Sempron2800+  阅读(132)  评论(0编辑  收藏  举报