Flip a binary tree (diagram, preorder traversal, recursive and non-recursive)

LCR 144. Flip Binary Tree - LeetCode

Given the root node of a binary tree root, please flip the binary tree left and right and return its root node.

Example 1:

Import:root = [5,7,9,8,3,2,4]
Output:[5,9,7,4,2,3,8]

hint:

  • The range of the number of nodes in the tree is within [0, 100] 
  • -100 <= Node.val <= 100

answer

Pre-order introductionEncyclopedia

 

 

code

recursive algorithm

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* mirrorTree(TreeNode* root) {
        if(!root) return nullptr;
        swap(root->left,root->right);
        mirrorTree(root->left);
        mirrorTree(root->right);
        return root;
    }
};

non-recursive algorithm

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* mirrorTree(TreeNode* root) {
        if(!root) return nullptr;
        stack<TreeNode*> s;
        s.push(root);
        while(!s.empty())
        {
            TreeNode* node=s.top();
            s.pop();
            swap(node->left,node->right);
            if(node->left) s.push(node->left);
            if(node->right) s.push(node->right);
        }

        return root;
    }
};

Guess you like

Origin blog.csdn.net/qq_58158950/article/details/134905318