226. Invert Binary Tree
发布时间:2020-12-14 04:19:37 所属栏目:大数据 来源:网络整理
导读: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 re
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,省略 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |