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

    C++代码,方法层序+互换左右孩子

     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         //层序遍历然后互换每一层的左右孩子
    14         if(root==NULL) return root;
    15         queue<TreeNode*> q;
    16         q.push(root);
    17         while(!q.empty()){
    18             TreeNode* cur=q.front();
    19             TreeNode* temp;
    20             q.pop();
    21             if(cur->left!=NULL) q.push(cur->left);
    22             if(cur->right!=NULL) q.push(cur->right);
    23             if(cur->left!=NULL&&cur->right==NULL){
    24                 cur->right=cur->left;cur->left=NULL;
    25             }else if(cur->left==NULL&&cur->right!=NULL){
    26                 cur->left=cur->right;cur->right=NULL;
    27             }else if(cur->left!=NULL&&cur->right!=NULL){
    28                 temp=cur->left;
    29                 cur->left=cur->right;
    30                 cur->right=temp;
    31             }
    32         }
    33         return root;
    34     }
    35 };
  • 相关阅读:
    android中文件操作的四种枚举
    【第4节】索引、视图、触发器、储存过程、
    【第3篇】数据库之增删改查操作
    【第2篇】基本操作和存储引擎
    【第1篇】数据库安装
    123
    111
    1111111
    源码
    【COLLECTION模块】
  • 原文地址:https://www.cnblogs.com/joelwang/p/10441137.html
Copyright © 2011-2022 走看看