zoukankan      html  css  js  c++  java
  • LeetCode: 226 Invert Binary Tree(easy)

    题目:

    Invert a binary tree.

         4
       /   
      2     7
     /    / 
    1   3 6   9
    to
         4
       /   
      7     2
     /    / 
    9   6 3   1
    代码:

    自己的(递归实现):

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     TreeNode* invertTree(TreeNode* root) {
    13         TreeNode* tem;
    14         if (!root)
    15             return 0;             
    16         tem = root->left;
    17         root->left = root->right;
    18         root->right = tem;
    19         if(root->left)
    20             invertTree(root->left);
    21         if(root->right)
    22             invertTree(root->right);
    23         return root;
    24     }
    25 };

    别人的:

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     TreeNode* invertTree(TreeNode* root) {
    13         if (root){
    14             swap(root->left, root->right);
    15             invertTree(root->left);
    16             invertTree(root->right);     
    17         }
    18         return root;
    19     }
    20 };

    自己的(使用队列,非递归实现):

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     TreeNode* invertTree(TreeNode* root) {
    13         queue<TreeNode*> queue;
    14         if(!root)
    15             return 0;
    16         queue.push(root);
    17         TreeNode *curNode;
    18         while(!queue.empty()){
    19             curNode = queue.front();
    20             queue.pop();
    21             swap(curNode->left, curNode->right);
    22             if(curNode->left)
    23                 queue.push(curNode->left);
    24             if(curNode->right)
    25                 queue.push(curNode->right);        
    26         }
    27         return root;
    28     }
    29 };

    非递归和递归的在LeetCode上运行效率差不多。。。

  • 相关阅读:
    软工实践个人总结
    第02组 Beta版本演示
    第02组 Beta冲刺(5/5)
    第02组 Beta冲刺(4/5)
    第02组 Beta冲刺(3/5)
    第02组 Beta冲刺(2/5)
    第02组 Beta冲刺(1/5)
    第02组 Alpha事后诸葛亮
    第02组 Alpha冲刺(6/6)
    第02组 Alpha冲刺(5/6)
  • 原文地址:https://www.cnblogs.com/llxblogs/p/7445551.html
Copyright © 2011-2022 走看看