首页 > 其他 > 详细

226. Invert Binary Tree

时间:2018-10-10 13:22:10      阅读:139      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!