[LeetCode] Construct String from Binary Tree

Posted immjc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] Construct String from Binary Tree相关的知识,希望对你有一定的参考价值。

Invert a binary tree.

     4
   /     2     7
 / \   / 1   3 6   9
to
     4
   /     7     2
 / \   / 9   6 3   1
Trivia:
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的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode&Python] Problem 427. Construct Quad Tree

LeetCode Construct String from Binary Tree

LeetCode:492. Construct the Rectangle

492. Construct the Rectangle(LeetCode)

leetcode-492-Construct the Rectangle

[LeetCode&Python] Problem 606. Construct String from Binary Tree