Skip to content

Latest commit

 

History

History
82 lines (63 loc) · 1.94 KB

226-invert-binary-tree.md

File metadata and controls

82 lines (63 loc) · 1.94 KB

226. Invert Binary Tree - 翻转二叉树

翻转一棵二叉树。

示例:

输入:

     4
   /   \
  2     7
 / \   / \
1   3 6   9

输出:

     4
   /   \
  7     2
 / \   / \
9   6 3   1

备注:
这个问题是受到 Max Howell 原问题 启发的 :

谷歌:我们90%的工程师使用您编写的软件(Homebrew),但是您却无法在面试时在白板上写出翻转二叉树这道题,这太糟糕了。

题目标签:Tree

题目链接:LeetCode / LeetCode中国

题解

Language Runtime Memory
cpp 0 ms N/A
/**
 * 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:
    TreeNode* invertTree(TreeNode* root) {
        if(!root){
            return root;
        }
        queue<TreeNode*> seq;
        set<TreeNode*> visit;
        visit.insert(root);
        seq.push(root);
        while(!seq.empty()){
            TreeNode* tmp = seq.front();
            seq.pop();
            swap(tmp->left, tmp->right);
            if(tmp->left && !visit.count(tmp->left)){
                visit.insert(tmp->left);
                seq.push(tmp->left);
            }
            if(tmp->right && !visit.count(tmp->right)){
                visit.insert(tmp->right);
                seq.push(tmp->right);
            }
        }
        return root;
    }
};