Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
分类:二叉树
题意:将二叉树转换成链表
解法1:递归。递归方法将返回链表的第一个节点。对于根节点而言,分别递归转换左右子树,然后找到左链表的最后一个节点(如果存在的话),连接该节点与右链表。
再用根节点连接左链表。
该方法超时,原因在于找左链表的最后一个节点,耗时。
-
-
-
-
-
-
-
-
-
- public class Solution {
- public void flatten(TreeNode root) {
- if(root==null) return ;
- flatten(root.left);
- flatten(root.right);
- TreeNode left = root.left;
- if(left==null) return;
- while(left.right!=null){
- left = left.right;
- }
- left.right = root.right;
- root.right = root.left;
- }
- }
解法2:递归解决。该方法返回转换成链表以后的最后一个节点。与解法1不同,先递归转换左子树,然后连接左链表跟右子树的第一个节点,接着在递归转换右子树。最后连接根节点和左链表。由于返回的是最后一个节点,省去方法1所说的找到最后一个节点的时间。
-
-
-
-
-
-
-
-
-
- public class Solution {
- public void flatten(TreeNode root) {
- helper(root);
- }
-
- TreeNode helper(TreeNode root){
- if(root==null) return null;
- TreeNode left = null;
- TreeNode right = null;
- if(root.left!=null){
- left = helper(root.left);
- if(left!=null){
- left.right = root.right;
- root.right = root.left;
- }
- root.left = null;
- }
- right = helper(root.right);
-
- if(right!=null)
- return right;
- else if(left!=null)
- return left;
- else
- return root;
- }
- }
解法3:使用栈。对于根节点,先后存入其左节点,右节点。然后将左节点连接到根节点的右边。至于其他节点,因为已经存在栈里面了。只要对于每个节点都重复上述过程,而不理会其子树。
-
-
-
-
-
-
-
-
-
- public class Solution {
- public void flatten(TreeNode root) {
- if(root==null) return;
- Stack<TreeNode> stack = new Stack<TreeNode>();
- stack.add(root);
- while(!stack.isEmpty()){
- TreeNode cur = stack.pop();
- if(cur.left!=null) stack.add(cur.left);
- if(cur.right!=null) stack.add(cur.right);
- cur.left=null;
- if(!stack.isEmpty()){
- cur.right = stack.peek();
- }
- }
- }
- }
原文链接http://blog.youkuaiyun.com/crazy__chen/article/details/46493951