您的位置:首页 > 其它

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:

/**
* 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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: