题目描述:给你一棵二叉树的根节点 root
,翻转这棵二叉树,并返回其根节点。
思路与算法:从根节点开始,递归地对树进行遍历,并从叶子节点先开始翻转。如果当前遍历到的节点 root 的左右两棵子树都已经翻转,只需交换两棵子树的位置,即可完成以 root 为根节点的整棵子树的翻转。
时间复杂度:O(n)
空间复杂度:O(n)
代码:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */
struct TreeNode* invertTree(struct TreeNode* root){ if(!root) return NULL; struct TreeNode* right, * left; right = invertTree(root->right); left = invertTree(root->left); root->right = left; root->left = right; return root; }
示例代码:
struct TreeNode* invertTree(struct TreeNode* root){ struct TreeNode* kkl; if(!root) return root; invertTree(root->left); invertTree(root->right); kkl=root->right; root->right=root->left; root->left=kkl; return root;标签:right,TreeNode,struct,invertTree,二叉树,easy,root,LeetCode,left From: https://www.cnblogs.com/elm-and-star/p/17375519.html
}