标签:
Recursive method can be unstand easily:
1. Assume we get the sub node with this transition. So we need to make the current node.
2. As the symmetic, the finished sub node will replace the position of current node.
3. old current->left = parent ->right, old current->right = parent, since we passed the these from argument. (one corner case : if parent == NULL, there is no parent->right)
This is a button up recursive:
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 TreeNode *getTree(TreeNode *root, TreeNode *parent) { 13 if (!root) return parent; //Find the most left, but root is NULL, so the new root is parent. 14 TreeNode *current = getTree(root->left, root); //This is sub node, but after conversion, it replace the current node. 15 root->left = parent == NULL ? NULL : parent->right; 16 root->right = parent; 17 return current; 18 } 19 TreeNode *upsideDownBinaryTree(TreeNode *root) { 20 return getTree(root, NULL); 21 } 22 };
Here‘s the top down iterative:
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 TreeNode *upsideDownBinaryTree(TreeNode *root) { 13 if (!root) return root; 14 TreeNode *parent = NULL, *parentRight = NULL; 15 while (root) { 16 TreeNode *lnode = root->left; 17 root->left = parentRight; 18 parentRight = root->right; 19 root->right = parent; 20 parent = root; 21 root = lnode; 22 } 23 return parent; 24 } 25 };
LeetCode – Refresh – Binary Tree Upside Down
标签:
原文地址:http://www.cnblogs.com/shuashuashua/p/4346213.html