Flatten Binary Tree to Linked List

来源:互联网 发布:手机编程用什么软件 编辑:程序博客网 时间:2024/06/08 05:34

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
非递归:
public class Solution {    public void flatten(TreeNode root) {        TreeNode now = root;        while(now != null){            if(now.left != null){                TreeNode pre = now.left;                while(pre.right != null){                    pre = pre.right;                }                pre.right = now.right;                now.right = now.left;                now.left = null;            }            now = now.right;        }    }}


递归:

public class Solution {    TreeNode pre = null;    public void flatten(TreeNode root) {        if(root == null) return;        flatten(root.right);        flatten(root.left);        root.right = pre;        root.left = null;        pre = root;    }}







0 0
原创粉丝点击