LeetCode Flatten Binary Tree to Linked List

来源:互联网 发布:淘宝图片轮播在线制作 编辑:程序博客网 时间:2024/06/05 10:41

题目:

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.

题意:

给一棵二叉树根据其前序遍历的结果重新生成一棵右子树。

题解:

此题,LZ考虑用递归方法首先来前序遍历,得到前序遍历之后的结果,并将这个结果保存在LinkedList中,然后重新将这个树输出,注意在输出树的时候,要当心第一个结点。

public class Solution {    LinkedList<Integer> list = new LinkedList<Integer>();public void flatten(TreeNode root){if(root == null)return;proorder(root);//TreeNode node = root;Iterator it = list.iterator();TreeNode node = root;int j = 0;while(it.hasNext()){    if(j != 0){    Integer i = (Integer)it.next();    TreeNode l = new TreeNode(i.intValue());    node.right = l;      //这儿每次都得考虑左子树和右子树的情况    node.left = null;    node = node.right;        //System.out.println(i.intValue());}else     it.next();j++;}}public void proorder(TreeNode root){list.add(root.val);if(root.left != null)proorder(root.left);if(root.right != null)proorder(root.right);}}

主要考虑递归调用来前序遍历。


0 0
原创粉丝点击