Binary Tree Upside Down Solutions in C++
Number 156
Difficulty Medium
Acceptance 55.1%
Link LeetCode
Other languages —
Solutions
C++ solution by haoel/leetcode
// Source : https://oj.leetcode.com/problems/binary-tree-upside-down/// Author : Hao Chen// Date : 2014-11-17/*** Definition for binary tree* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/class Solution {public:TreeNode *upsideDownBinaryTree(TreeNode *root) {//using a dummy node to help to store the new treeTreeNode dummy(0);TreeNode *head = &dummy, *left=NULL, *right=NULL;while ( root!=NULL ) {//find the right & leftleft = root->right;right = root;//move root the nextroot = root->left;//replace the right with current rootright->left = head->left;right->right = head->right;//move the dummy to the rootdummy.right = right;dummy.left = left;//reset the head to the roothead = &dummy;}return head->right;}};