/**
* 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:
void dfs(TreeNode* now){
TreeNode* t = now->left;
now->left = now->right;
now->right = t;
if(now->left!=NULL) dfs(now->left);
if(now->right != NULL) dfs(now->right);
}
TreeNode* invertTree(TreeNode* root) {
if(root == NULL) return NULL;
dfs(root);
return root;
}
};
No.135 - LeetCode226 - (经典)二叉树左右翻转
最新推荐文章于 2024-03-26 22:36:59 发布
本文介绍了一种用于翻转二叉树节点的深度优先搜索(DFS)算法。通过递归方式交换每个节点的左子树和右子树,实现了整个二叉树结构的翻转。此算法在计算机科学和数据结构领域中有着广泛的应用。
481

被折叠的 条评论
为什么被折叠?



