码迷,mamicode.com
首页 > 其他好文 > 详细

[LC] 156. Binary Tree Upside Down

时间:2020-01-15 13:37:21      阅读:80      评论:0      收藏:0      [点我收藏+]

标签:nod   lin   with   sibling   HERE   either   des   roo   turn   

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.

Example:

Input: [1,2,3,4,5]

    1
   /   2   3
 / 4   5

Output: return the root of the binary tree [4,5,2,#,#,3,1]

   4
  /  5   2
    /    3   1 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode upsideDownBinaryTree(TreeNode root) {
        if (root == null || root.left == null) {
            return root;
        }
        TreeNode newNode = upsideDownBinaryTree(root.left);
        root.left.left = root.right;
        root.left.right = root;
        root.left = null;
        root.right = null;
        return newNode;
    }
}

[LC] 156. Binary Tree Upside Down

标签:nod   lin   with   sibling   HERE   either   des   roo   turn   

原文地址:https://www.cnblogs.com/xuanlu/p/12196022.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!