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

    题目

    题目

    分析

    交换二叉树的左右子树。

    递归非递归两种方法实现。

    AC代码

    class Solution {
    public:
        //递归实现
        TreeNode* invertTree(TreeNode* root) {
            if (!root)
                return root;
    
            TreeNode *tmp = root->left;
            root->left = invertTree(root->right);
            root->right = invertTree(tmp);
    
            return root;
        }
    
        //非递归实现
        TreeNode* invertTree2(TreeNode* root) {
            if (root == NULL)
                return root;
            queue<TreeNode*> tree_queue;
            tree_queue.push(root);
    
            while (!tree_queue.empty()){
                TreeNode * pNode = tree_queue.front();
                tree_queue.pop();
    
                TreeNode * pLeft = pNode->left;
                pNode->left = pNode->right;
                pNode->right = pLeft;
    
                if (pNode->left)
                    tree_queue.push(pNode->left);
                if (pNode->right)
                    tree_queue.push(pNode->right);
            }
            return root;
        }
    };
  • 相关阅读:
    NYOJ 35
    TOJ 3072
    HDU 1075
    POJ 1028
    TOJ 1153
    TOJ 1036
    POJ 1521
    POJ 3253
    NYOJ 467
    HDU 1671
  • 原文地址:https://www.cnblogs.com/shine-yr/p/5214732.html
Copyright © 2011-2022 走看看