博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode: Binary Tree Upside Down
阅读量:4563 次
发布时间:2019-06-08

本文共 1624 字,大约阅读时间需要 5 分钟。

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 5return the root of the binary tree [4,5,2,#,#,3,1]. 4 / \ 5 2 / \ 3 1

这题第一眼看上去觉得没头绪,不知道怎么上下翻转和左右翻转。但在纸上画几个例子就清楚了。所有的右子树要么为空、要么就是叶子节点且有左子树存在。

那么原来的数一直沿左子树走下去最左的那个节点就是新树的根节点。

这道题最关键在于想到要用递归去做!这种树的结构、父子两层节点关系的问题多半都要用递归去做。这是大方向。我最开始想到用stack, 用hashmap来存然后用迭代都有点复杂。递归就很简单。

一旦确定递归,问题就迎刃而解了,就是一直往左走到叶子节点,返回该点作为新的根节点newRoot,定义newRoot.left, newRoot.right, 再返回newRoot.right作为上一层的newRoot。

注意递归函数最终返回的节点并非我们所求,如上图返回1节点,而我们需要新树的root节点:节点4. 所以在递归里加一个argument,ArrayList<TreeNode>, 来包裹新root节点当找到它时。这是java函数参数传递问题,如果直接用TreeNode作为argument, 传的是引用,函数里引用所指的地址发生改变,不会让函数外的引用所指的地址改变

1 public class Solution { 2     public TreeNode UpsideDownBinaryTree(TreeNode root) { 3         if (root == null) return null; 4         ArrayList
res = new ArrayList
(); 5 res.add(null); 6 helper(root, res); 7 return res.get(0); 8 } 9 10 public TreeNode helper(TreeNode root, ArrayList
res) {11 if (root.left == null) {12 res.set(0, root);13 return root;14 }15 TreeNode newRoot = helper(root.left, res);16 newRoot.left = root.right;17 newRoot.right = root;18 return newRoot.right;19 }20 }

 

转载于:https://www.cnblogs.com/EdwardLiu/p/4232896.html

你可能感兴趣的文章
Ubuntu上kubeadm安装Kubernetes集群
查看>>
关于java学习中的一些易错点(基础篇)
查看>>
MFC的多国语言界面的实现
查看>>
四则运算个人项目 最终版
查看>>
java线程系列---java5中的线程池
查看>>
SQL表连接
查看>>
新秀系列C/C++经典问题(四)
查看>>
memset函数具体说明
查看>>
经常使用的android弹出对话框
查看>>
确保新站自身站点设计的合理性的六大注意点
查看>>
深入浅出HTTPS基本原理
查看>>
promise
查看>>
Go 网络编程笔记
查看>>
[]Java面试题123道
查看>>
http 连接复用
查看>>
ASP.NET页面传值汇总
查看>>
观察者模式
查看>>
bundle update: env: ruby_executable_hooks: No such file or directory
查看>>
Linux重置mysql密码(转载)
查看>>
图片上传
查看>>