算法设计与应用基础

来源:互联网 发布:dota2饰品淘宝 编辑:程序博客网 时间:2024/06/06 20:52

226. Invert Binary Tree

Invert a binary tree.


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


Recursive

TreeNode* invertTree(TreeNode* root) {    if (root) {        invertTree(root->left);        invertTree(root->right);        std::swap(root->left, root->right);    }    return root;}

Non-Recursive

TreeNode* invertTree(TreeNode* root) {    std::stack<TreeNode*> stk;    stk.push(root);        while (!stk.empty()) {        TreeNode* p = stk.top();        stk.pop();        if (p) {            stk.push(p->left);            stk.push(p->right);            std::swap(p->left, p->right);        }    }    return root;}


原创粉丝点击