LeetCode – Refresh – Binary Tree Upside Down
2015-03-18 08:57
447 查看
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:
Here's the top down iterative:
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:
/** * 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 *getTree(TreeNode *root, TreeNode *parent) { if (!root) return parent; //Find the most left, but root is NULL, so the new root is parent. TreeNode *current = getTree(root->left, root); //This is sub node, but after conversion, it replace the current node. root->left = parent == NULL ? NULL : parent->right; root->right = parent; return current; } TreeNode *upsideDownBinaryTree(TreeNode *root) { return getTree(root, NULL); } };
Here's the top down iterative:
/** * 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) { if (!root) return root; TreeNode *parent = NULL, *parentRight = NULL; while (root) { TreeNode *lnode = root->left; root->left = parentRight; parentRight = root->right; root->right = parent; parent = root; root = lnode; } return parent; } };
相关文章推荐
- 【LeetCode】Binary Tree Upside Down
- [LeetCode] Binary Tree Upside Down
- Leetcode Binary Tree Upside Down
- [Leetcode] Binary Tree Upside Down
- [LeetCode]156 Binary Tree Upside Down
- [Leetcode] Binary Tree Upside Down
- [LeetCode 156] Binary Tree Upside Down
- leetcode--Binary Tree Upside Down
- LeetCode "Binary Tree Upside Down"
- LeetCode-Binary Tree Upside Down
- leetcode--Binary Tree Upside Down
- LeetCode Binary Tree Upside Down
- [LeetCode] Binary Tree Upside Down 二叉树的上下颠倒
- leetcode[156]Binary Tree Upside Down
- [LeetCode156] Binary Tree Upside Down
- leetcode 156: Binary Tree Upside Down
- [LeetCode156] Binary Tree Upside Down
- [LeetCode] Binary Tree Upside Down的三种解法
- LeetCode Binary Tree Upside Down
- [leetcode] Binary Tree Upside Down