leetcode_114_Flatten Binary Tree to Linked List

141 篇文章 4 订阅
132 篇文章 1 订阅

描述:

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

click to show hints.

Hints:

If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.

思路:

按照中序遍历的方式将结点存储到一个list列表中,然后分别将各个节点的left赋值为空,将right指向下一个节点,最后将最后一个结点的right赋值为空即可生成题目要求的树结构。结果对了是对了,好像不太符合题目要求,题目要求 do it in-place,不知道我的算不算in place。很显然,从时间上来看,我想到的思路也不能算好。刚开始以为是要生成一个链表,走了好多弯路,发现返回值就是一个void,题目要实现的就是改变下树是结构而已。

代码:

class TreeNode{
		int val;
		TreeNode left;
		TreeNode right;
		TreeNode(int x){val=x;}
	}
    public void flatten(TreeNode root) 
    {
    	List<TreeNode>list=new ArrayList<TreeNode>();
	     if(root==null)
			 return ;
	     Stack<TreeNode>st=new Stack<TreeNode>();
	     st.push(root);
	     TreeNode top=null;
	     list.add(root);
	     while(!st.empty())
	     {
	    	 top=st.peek();
	    	 while(top.left!=null)
	    	 {
	    		 st.push(top.left);
	    		 list.add(top.left);
	    		 top=top.left;
	    	 }
	    	 while(top.right==null)
	    	 {
	    		 
	    		 st.pop();
	    		 if(!st.empty())
	    			 top=st.peek();
	    		 else
	    			 break;
	    	 }
	    	 if(!st.empty())
	    	 {
		    	 st.pop();
		    	 st.push(top.right);
		    	 list.add(top.right);
	    	 }
	    	 
	     }
	     int len=list.size();
	     TreeNode pre =list.get(0),cur=null;
	     for(int i=1;i<len;i++)
	     {
	    	 cur=list.get(i);
	    	 pre.right=cur;
	    	 pre.left=null;
	    	 pre=cur;
	     }
	     cur=list.get(len-1);
	     cur.left=null;
	     cur.right=null;
	     
    }

结果:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值