Flatten Binary Tree to Linked List

来源:互联网 发布:游戏碎片整理软件 编辑:程序博客网 时间:2024/05/22 09:47
/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    // Pre-order traverse, append current node to the linked list.    private static TreeNode linkedListEnd = null;    public void flatten(TreeNode root) {        if (root == null) return;        TreeNode left = root.left;        TreeNode right = root.right;        if (linkedListEnd != null){            // Append current node to linked list            linkedListEnd.right = root;            linkedListEnd.left = null;        } // If linked list is empty, just set root to linkedListEnd        linkedListEnd = root;        flatten(left);        flatten(right);    }}

0 0