其他分享
首页 > 其他分享> > LeetCode 226 Invert Binary Tree DFS

LeetCode 226 Invert Binary Tree DFS

作者:互联网

Given the root of a binary tree, invert the tree, and return its root.

Solution:

直接使用 \(DFS\) 进行递归即可:

点击查看代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
private:
    void dfs(TreeNode* root){
        if(!root)return;
        swap(root->right, root->left);
        dfs(root->right);dfs(root->left);
    }
public:
    TreeNode* invertTree(TreeNode* root) {
        if(root==NULL) return NULL;
        dfs(root);
        return root;
    }
};

标签:Binary,right,TreeNode,val,nullptr,Invert,Tree,root,left
来源: https://www.cnblogs.com/xinyu04/p/16492620.html