LeetCode:226. Invert Binary Tree(倒转一棵二叉树)

客官°小女子只卖身不卖艺 2022-04-12 02:54 280阅读 0赞

文章最前: 我是Octopus,这个名字来源于我的中文名—章鱼;我热爱编程、热爱算法、热爱开源。

这博客是记录我学习的点点滴滴,如果您对 Python、Java、AI、算法有兴趣,可以关注我的动态,一起学习,共同进步。

相关文章:

  1. LeetCode:55. Jump Game(跳远比赛)
  2. Leetcode:300. Longest Increasing Subsequence(最大增长序列)
  3. LeetCode:560. Subarray Sum Equals K(找出数组中连续子串和等于k)

文章目录:

题目描述:

java实现方法1:

python实现方式1:

java实现方法2:

python实现方式2:

源码地址:


题目描述:

翻转一棵二叉树。

输入:

  1. 4
  2. / \
  3. 2 7
  4. / \ / \
  5. 1 3 6 9

输出:

  1. 4
  2. / \
  3. 7 2
  4. / \ / \
  5. 9 6 3 1

来源:力扣(LeetCode)


java实现方法1:

  1. /**
  2. * 反转一棵二叉树
  3. *
  4. * @param root 根节点
  5. * @return 反转后的二叉树
  6. */
  7. public TreeNode invertTree(TreeNode root) {
  8. if (root == null) {
  9. return null;
  10. }
  11. TreeNode left = invertTree(root.left);
  12. TreeNode right = invertTree(root.right);
  13. root.left = right;
  14. root.right = left;
  15. return root;
  16. }

时间复杂度:O(n)

空间复杂度:O(n)


python实现方式1:

  1. def invert_tree(self, root: TreeNode) -> TreeNode:
  2. '''
  3. 翻转二叉树
  4. Args:
  5. root: 根节点
  6. Returns:
  7. TreeNode
  8. '''
  9. if root == None:
  10. return None
  11. left = self.invert_tree(root.left)
  12. right = self.invert_tree(root.right)
  13. root.left = right
  14. root.right = left
  15. return root

时间复杂度:O(n)

空间复杂度:O(n)


java实现方法2:

  1. /**
  2. * 反转一棵二叉树
  3. *
  4. * @param root 根节点
  5. * @return 反转后的二叉树
  6. */
  7. public TreeNode invertTree2(TreeNode root) {
  8. if (root == null) {
  9. return null;
  10. }
  11. LinkedList<TreeNode> list = new LinkedList<>();
  12. list.add(root);
  13. while (!list.isEmpty()) {
  14. TreeNode cur = list.poll();
  15. if (cur.left != null) {
  16. list.add(cur.left);
  17. }
  18. if (cur.right != null) {
  19. list.add(cur.right);
  20. }
  21. TreeNode temp = cur.right;
  22. cur.right = cur.left;
  23. cur.left = temp;
  24. }
  25. return root;
  26. }

时间复杂度:O(n)

空间复杂度:O(n)


python实现方式2:

  1. def invert_tree2(self, root: TreeNode) -> TreeNode:
  2. '''
  3. 翻转二叉树
  4. Args:
  5. root: 根节点
  6. Returns:
  7. TreeNode
  8. '''
  9. if root == None:
  10. return None
  11. node_list = []
  12. node_list.append(root)
  13. while len(node_list) > 0:
  14. cur = node_list.pop()
  15. if cur.left:
  16. node_list.append(cur.left)
  17. if cur.right:
  18. node_list.append(cur.right)
  19. temp = cur.right
  20. cur.right = cur.left
  21. cur.left = temp
  22. return root

时间复杂度:O(n)

空间复杂度:O(n)


源码地址:

https://github.com/zhangyu345293721/leetcode

发表评论

表情:
评论列表 (有 0 条评论,280人围观)

还没有评论,来说两句吧...

相关阅读