Binary Tree Upside Down

题目
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.

答案
刚开始没看懂题目什么意思,怎么flip??
看着题目的例子找下规律就懂了

class Solution {
    public TreeNode upsideDownBinaryTree(TreeNode root) {
        if(root == null) return null;
        TreeNode ret = recur(root, null);
        return ret;
    }

    public TreeNode recur(TreeNode root, TreeNode parent) {
        TreeNode ret;
        if(root.left == null && root.right == null) ret = root;
        else ret = recur(root.left, root);
        
        root.right = parent;
        if(parent != null) {
            root.left = parent.right;
            parent.left = null;
            parent.right = null;
        }
        return ret;
    }

}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容