博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Flatten Binary Tree to Linked List
阅读量:6681 次
发布时间:2019-06-25

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

Note:

It is easier to use divided conquer. As you can see, the question is just to add right to left's last. Here we care more about last then the top because top can always be traced by root. Since the right is the last if it is null, first return right and then check left side. 

/** * Definition of TreeNode: * public class TreeNode { *     public int val; *     public TreeNode left, right; *     public TreeNode(int val) { *         this.val = val; *         this.left = this.right = null; *     } * } */public class Solution {    /**     * @param root: a TreeNode, the root of the binary tree     * @return: nothing     */    public void flatten(TreeNode root) {        // write your code here        flattenTree(root);    }        private TreeNode flattenTree(TreeNode root) {        if (root == null) {            return root;        }                //This problem is looking for the last element        TreeNode leftLast = flattenTree(root.left);        TreeNode rightLast = flattenTree(root.right);                if (leftLast != null) {            leftLast.right = root.right;            root.right = root.left;            root.left = null;        }                if (rightLast != null) {            return rightLast;        }                if (leftLast != null) {            return leftLast;        }                return root;    }}

 

// The traverse version. Please check http://www.jiuzhang.com/solutions/flatten-binary-tree-to-linked-list/

转载于:https://www.cnblogs.com/codingEskimo/p/6931577.html

你可能感兴趣的文章
mysql实时记录客户端提交的sql语句
查看>>
多线程学习笔记(五)
查看>>
pyspider爬虫学习-教程3-Render-with-PhantomJS.md
查看>>
107个常用Javascript语句
查看>>
关联表更新
查看>>
Java递归拷贝文件夹
查看>>
从Java到C++——从union到VARIANT与CComVariant的深层剖析
查看>>
java使用jeids实现redis2.6的list操作(3)
查看>>
Android简单框架会用到的基类(2)
查看>>
flask sqlalchemy多个外键引用同张表报错sqlalchemy.exc.AmbiguousForeignKeysError
查看>>
在 CentOS6 上安装 Python 2 & 3
查看>>
svnserver配置文件详解
查看>>
Mybatis之动态SQL语句
查看>>
文件上传利器SWFUpload使用指南
查看>>
jdbc性能优化
查看>>
linux下activemq异常退出,重启失败
查看>>
WordPress条件判断标签(Conditional Tags)手册
查看>>
【05】中级:翻页采集(以微博博主主页采集为例)
查看>>
iOS不规则按钮的响应事件的处理方法
查看>>
Linux下密码过期时间设置
查看>>