首页 > 代码库 > [LeetCode] Construct String from Binary Tree
[LeetCode] Construct String from Binary Tree
Invert a binary tree.
to4 / 2 7 / \ / 1 3 6 9
Trivia:4 / 7 2 / \ / 9 6 3 1
This problem was inspired by this original tweet by Max Howell:
Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.
反转一个二叉树,使用递归很容易就可以实现。递归交换节点即可。
class Solution { public: TreeNode* invertTree(TreeNode* root) { if (root == nullptr) return 0; root->left = invertTree(root->left); root->right = invertTree(root->right); swap(root->left, root->right); return root; } }; // 0 ms
使用迭代实现
class Solution { public: TreeNode* invertTree(TreeNode* root) { if (root == nullptr) return 0; stack<TreeNode*> s; s.push(root); while (!s.empty()) { TreeNode* node = s.top(); s.pop(); if (node->left != nullptr) s.push(node->left); if (node->right != nullptr) s.push(node->right); swap(node->left, node->right); } return root; } }; // 0 ms
[LeetCode] Construct String from Binary Tree
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。