zoukankan      html  css  js  c++  java
  • 刷题226. Invert Binary Tree

    一、题目说明

    题目226. Invert Binary Tree,翻转一个二叉树。难度是Easy!

    二、我的解答

    这个题目,和二叉树的遍历类似。用递归方法(前、中、后序遍历,按层遍历都可以):

    class Solution{
    	public:
    		TreeNode* invertTree(TreeNode* root){
    			if(root ==NULL) return root;
    			TreeNode * p = root->left;
    			root->left = root->right;
    			root->right = p;
    			root->left = invertTree(root->left);
    			root->right = invertTree(root->right);
    			return root;
    		}
    };
    

    性能如下:

    Runtime: 4 ms, faster than 65.13% of C++ online submissions for Invert Binary Tree.
    Memory Usage: 10 MB, less than 5.45% of C++ online submissions for Invert Binary Tree.
    

    三、优化措施

    非递归的算法,下面用广度优先遍历实现:

    class Solution{
    	public:
    		//non-recursive using level
    		TreeNode* invertTree(TreeNode* root){
    			if(root == NULL) return root;
    			queue<TreeNode*> q;
    			TreeNode* tmp,*cur;
    			q.push(root);
    			while(! q.empty()){
    				cur = q.front();
    				q.pop();
    				tmp = cur->left;
    				cur->left = cur->right;
    				cur->right = tmp;
    				if(cur->left !=NULL ){
    					q.push(cur->left);
    				}
    				if(cur->right != NULL){
    					q.push(cur->right);
    				}
    			}
    			
    			return root;
    		}
    };
    

    性能如下:

    Runtime: 0 ms, faster than 100.00% of C++ online submissions for Invert Binary Tree.
    Memory Usage: 10.2 MB, less than 5.45% of C++ online submissions for Invert Binary Tree.
    
    所有文章,坚持原创。如有转载,敬请标注出处。
  • 相关阅读:
    十分简单的宏病毒
    爬虫入门六 总结 资料 与Scrapy实例-bibibili番剧信息
    爬虫入门五 gooseeker
    爬虫入门四 re
    爬虫入门三 scrapy
    爬虫入门二 beautifulsoup
    爬虫入门一 基础知识 以及request
    腾讯游戏策划实习面经
    网络安全实验合集
    HTML5总结
  • 原文地址:https://www.cnblogs.com/siweihz/p/12287374.html
Copyright © 2011-2022 走看看