/**
* 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);
}
}
Flatten Binary Tree to Linked List
最新推荐文章于 2022-09-06 16:04:14 发布