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

[LeetCode] 156. Binary Tree Upside Down

时间:2020-05-01 15:02:12      阅读:55      评论:0      收藏:0      [点我收藏+]

标签:inpu   翻转   div   左右   nod   NPU   color   solution   联系   

上下翻转二叉树。题意是给一个二叉树,请你翻转一下。我的理解是基本是把这个二叉树顺时针旋转120度的感觉。例子,

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  

如上图,最小的左孩子成了根节点,而原来的根节点成了最小的右孩子。我这里给出递归的做法,首先找到新的根节点,然后将新的根节点跟他的左右孩子分别连好,然后再断开原来的根节点及其左右孩子的联系。

时间O(n)

空间O(n)

Java实现

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode() {}
 8  *     TreeNode(int val) { this.val = val; }
 9  *     TreeNode(int val, TreeNode left, TreeNode right) {
10  *         this.val = val;
11  *         this.left = left;
12  *         this.right = right;
13  *     }
14  * }
15  */
16 class Solution {
17     public TreeNode upsideDownBinaryTree(TreeNode root) {
18         // corner case
19         if (root == null || root.left == null && root.right == null) {
20             return root;
21         }
22         
23         // normal case
24         TreeNode newRoot = upsideDownBinaryTree(root.left);
25         root.left.left = root.right;
26         root.left.right = root;
27         root.left = null;
28         root.right = null;
29         return newRoot;
30     }
31 }

 

[LeetCode] 156. Binary Tree Upside Down

标签:inpu   翻转   div   左右   nod   NPU   color   solution   联系   

原文地址:https://www.cnblogs.com/aaronliu1991/p/12813158.html

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