[LeetCode156] Binary Tree Upside Down

今天开始先把leetcode收费题思路整理到这里,因为只买了一个月。。。==, 用中文吗。

Binary Tree Upside Down My Submissions Question
Total Accepted: 6016 Total Submissions: 16909 Difficulty: Medium
Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that shares the same parent node) or empty, flip it upside down and turn it into a tree where the original right nodes turned into left leaf nodes. Return the new root.

For example:
Given a binary tree {1,2,3,4,5},
                                1
                               / \
                              2   3
                             / \
                            4   5
return the root of the binary tree [4,5,2,#,#,3,1].
                               4
                              / \
                             5   2
                                / \
                               3   1  
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

思路:
这道题从例子分析,所谓upside down,就是: oldroot->new right child, oldLeft -> new root and oldRight->new left chid.
做了这么多题, 感觉这种binary tree的题一般都用recursion可以解决, 但每次!细节都有问题。
啊,补充一下,这道题有一点很重要就是:old->left = old->right = nullptr. 用完oldroot的left和right之后要把它们设成null。
recursion的重点除了要返回新node的right child,最终我们还要返回最终的new root, 所以需要找到newroot!
update: 11/28/2015发现iterative w/ stack更直观,就更新一下哟。。。

    TreeNode* upsideDownBinaryTree(TreeNode* root) {
        TreeNode* newRoot = nullptr;
        build(root, newRoot);
        return newRoot;
    }
    void build(TreeNode* node, TreeNode*& newRoot){
        if(!node) return;
        if(node->left){
            build(node->left, newRoot);
            node->left->left = node->right;
            node->left->right = node;
        }else newRoot = node;// find newRoot
        node->left = node->right = nullptr;
    }

Another method w/o helper function:

    TreeNode* upsideDownBinaryTree(TreeNode* root) {
        if(!root || !root->left) return root;
        TreeNode* newRoot = upsideDownBinaryTree(root->left);
        root->left->left = root->right;
        root->left->right = root;
        root->left = root->right = nullptr;
        return newRoot;
    }

iteration code:

    TreeNode* upsideDownBinaryTree(TreeNode* root) {
        if(!root || !root->left) return root;
        stack<TreeNode*> stk;
        while(root){
            stk.push(root);
            root = root->left;
        }
        TreeNode* newRoot = stk.top();
        stk.pop();
        TreeNode* cur = newRoot;
        while(!stk.empty()){
            cur->left = stk.top()->right;
            cur->right = stk.top();
            cur = cur->right;
            cur->left = cur->right = nullptr; //please remember to set left and right child to be nullptr!!!
            stk.pop();
        }
        return newRoot;
    }

你可能感兴趣的:(LeetCode)