zoukankan      html  css  js  c++  java
  • 【07_226】Invert Binary Tree

    Invert Binary Tree

    Total Accepted: 54994 Total Submissions: 130742 Difficulty: Easy

    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.

     
     
    通过这道题,好好理解了递归。
    递归返回的是什么要考虑清楚,
    可以仔细研磨这道题,很好的题。
     
     
    C语言
     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     struct TreeNode *left;
     6  *     struct TreeNode *right;
     7  * };
     8  */
     9 struct TreeNode* invertTree(struct TreeNode* root) {
    10     if (root == NULL)
    11         return root;
    12     if (root->left == NULL && root->right == NULL)
    13         return root;
    14     else{
    15         struct TreeNode* temp = root->right;
    16         root->right = root->left;
    17         root->left = temp;
    18     }
    19     root->left = invertTree(root->left);
    20     root->right = invertTree(root->right);
    21     
    22     return root;
    23 }

    下面是在网上找的一种解法,C++写的。由于这是对实际树的结构进行操作,所以说可以不特别管返回值。

    1 TreeNode* invertTree(TreeNode* root) {
    2     if (root) {
    3         invertTree(root->left);
    4         invertTree(root->right);
    5         std::swap(root->left, root->right);
    6     }
    7     return root;
    8 }
  • 相关阅读:
    2-SAT模板
    AC自动机
    省选预备营-Day3(图论) 总结
    省选预备营-Day2(分治) 总结
    左偏树(可并堆)总结
    省选预备营-Day1(数据结构) 总结
    OI基础知识
    C++ 堆
    CH4601 普通平衡树
    java 函数形参传值和传引用的区别
  • 原文地址:https://www.cnblogs.com/QingHuan/p/5042502.html
Copyright © 2011-2022 走看看