zoukankan      html  css  js  c++  java
  • leetcode: invert binary tree

    1. 问题描述:

      旋转一颗二叉树(每一个节点的左右子数都要交换)

    2. 解答:

      这题没看答案之前我是用后序遍历(先左后右最后中)去做的,很奇怪自己为什么没有一开始就想到更符合直觉的先序遍历~~~

           本人算法的伪代码 :

           function invert (root) 

        if root为空 then

          end function

        end if

        invert(root左子树)

        invert(root右子树)

        交换root左右子树

      end function

      相应的java代码:

      

     1 public class Solution {
     2     public TreeNode invertTree(TreeNode root) {
     3         if (root == null)
     4             return root;
     5         TreeNode lt = root.getLeft();
     6         TreeNode rt = root.getRight();
     7 
     8         invertTree(lt);
     9         invertTree(rt);
    10         TreeNode temp = lt;
    11         root.setLeft(rt);
    12         root.setRight(temp);
    13         
    14         return root;
    15     }
    16 }
    View Code

      

      在看一下网上先序遍历算法的伪代码:

      function invert(root):

        if root为空

          end function

        end if

        交换root左右子树

        invert(root左子树)

        invert(root右子树)

      end function

  • 相关阅读:
    [转载]Sublime Text 3 搭建 React.js 开发环境
    浏览器缓存之Expires Etag Last-Modified max-age详解
    第16周作业
    第15周作业
    第14周作业
    第13周作业集
    软件工程结课作业
    第13次作业--邮箱的正则表达式
    第12次作业--你的生日
    第11次作业--字符串处理
  • 原文地址:https://www.cnblogs.com/yxmfighting/p/7141240.html
Copyright © 2011-2022 走看看