leetCode练习(114)

题目:Flatten Binary Tree to Linked List

难度:medium

问题描述:

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

解题思路:

一种方法是前序遍历,生成新的链表树输出即可。由于要创建大量节点,费时费力,效率低下。

这里使用递归法解题。root的左子树=null,右子树=左子树的递归+右子树的递归。

代码如下:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void flatten(TreeNode root) {
        treetolist(root);
    }
    private TreeNode treetolist(TreeNode root){
		if(root==null) return null;
		TreeNode right=treetolist(root.right);	
		root.right=treetolist(root.left);
		root.left=null;
		TreeNode temp=root;
		while(temp.right!=null){
			temp=temp.right;
		}
		temp.right=right;
		return root;
	}
}

你可能感兴趣的:(leetCode)