码迷,mamicode.com
首页 > 其他好文 > 详细

226. Invert Binary Tree

时间:2018-10-10 14:32:45      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:ide   put   ott   span   turn   bfs   color   return   nod   

Invert a binary tree.

Example:

Input:

     4
   /     2     7
 / \   / 1   3 6   9

Output:

     4
   /     7     2
 / \   / 9   6 3   1
 1 //Time: O(n), Space: O(h)/O(logn) 
 2 //Approach 1: DFS Top down recursive
 3    public TreeNode invertTree(TreeNode root) {
 4         if (root == null) {
 5             return null;
 6         }
 7         
 8         TreeNode temp = root.left;
 9         root.left = invertTree(root.right);
10         root.right = invertTree(temp);
11         return root;
12     }
13 
14 //Approach 2: DFS Bottom up recursive(Divide and Concur)
15     public TreeNode invertTree(TreeNode root) {
16         if (root == null) {
17             return null;
18         }
19         
20         TreeNode left = invertTree(root.left);
21         TreeNode right = invertTree(root.right);
22         root.left = right;
23         root.right = left;
24         return root;
25     }
26 //Approach3: BFS Queue, 省略

 

226. Invert Binary Tree

标签:ide   put   ott   span   turn   bfs   color   return   nod   

原文地址:https://www.cnblogs.com/jessie2009/p/9765694.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!