zoukankan      html  css  js  c++  java
  • 226 翻转二叉树 Invert Binary Tree


    Invert a binary tree.

         4
       /   
      2     7
     /    / 
    1   3 6   9
    to
         4
       /   
      7     2
     /    / 
    9   6 3   1
    Trivia:
    This problem was inspired by this original tweet by Max Howell:
    Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.

    翻转二叉树
    1. /**
    2. * Definition for a binary tree node.
    3. * public class TreeNode {
    4. * public int val;
    5. * public TreeNode left;
    6. * public TreeNode right;
    7. * public TreeNode(int x) { val = x; }
    8. * }
    9. */
    10. public class Solution {
    11. public TreeNode InvertTree(TreeNode root) {
    12. if(root==null||(root.left==null&&root.right==null)) return root;
    13. var tem = root.left;
    14. root.left = root.right;
    15. root.right = tem;
    16. if(root.right!=null){
    17. InvertTree(root.right);
    18. }
    19. if(root.left!=null){
    20. InvertTree(root.left);
    21. }
    22. return root;
    23. }
    24. }

    payhon BFS版
    1. class Solution(object):
    2. def invertTree(self, root):
    3. """
    4. :type root: TreeNode
    5. :rtype: TreeNode
    6. """
    7. if (not root):
    8. return
    9. queue = [root]
    10. while (queue):
    11. node = queue.pop(0)
    12. node.left,node.right = node.right,node.left
    13. if(node.left):
    14. queue.append(node.left)
    15. if(node.right):
    16. queue.append(node.right)
    17. return root







  • 相关阅读:
    设置CentOS7 静态获取IP
    视图与索引
    常用sql语句--DQL
    数据完整性
    常用sql语句--DML
    常用数据类型
    常用sql语句--DDL
    命令提示符内简单操作MySQL
    cnpm安装教程
    js生成指定范围的随机整数
  • 原文地址:https://www.cnblogs.com/xiejunzhao/p/be32126d73d3e29d4d97ac07f6c3de37.html
Copyright © 2011-2022 走看看