递归---Flatten Binary Tree to Linked List

来源:互联网 发布:欧美网络教育本科文凭 编辑:程序博客网 时间:2024/06/05 15:47

Flatten a binary tree to a fake “linked list” in pre-order traversal.

Here we use the right pointer in TreeNode as the next pointer in ListNode.

public class Solution {    private TreeNode lastNode = null;    public void flatten(TreeNode root) {        if (root == null) {            return;        }        if (lastNode != null) {            lastNode.left = null;            lastNode.right = root;        }        lastNode = root;        TreeNode right = root.right;        flatten(root.left);        flatten(right);    }}
0 0
原创粉丝点击