标签:
Recursion, a natural thought:
class Solution { // Top : BottomRight std::pair<TreeNode *, TreeNode *> rotate(TreeNode *p) { if (!p->left && !p->right) { return make_pair(p, p); } auto r = rotate(p->left); r.second->left = p->right; r.second->right = p; if (p->right) p->right->left = p->right->right = nullptr; p->left = p->right = nullptr; return make_pair(r.first, p); } public: TreeNode* upsideDownBinaryTree(TreeNode* root) { if (!root) return root; auto r = rotate(root); return r.first; } };
Iterative, just picture it in your mind :)
class Solution { public: TreeNode* upsideDownBinaryTree(TreeNode* root) { TreeNode *cur = root, *p = nullptr, *pr = nullptr; while(cur) { // Rotate auto left = cur->left; // store cur->left = pr; pr = cur->right; // move on cur->right= p; // Move on left-wards p = cur; cur = left; } return p; } };
LeetCode "Binary Tree Upside Down"
标签:
原文地址:http://www.cnblogs.com/tonix/p/4744892.html