首页 > 其他 > 详细

[LeetCode] Construct String from Binary Tree

时间:2017-07-11 22:22:23      阅读:313      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/immjc/p/7152418.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!