Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/83f756fa16108bcd7d806356d76c5ac2 to your computer and use it in GitHub Desktop.
Save jianminchen/83f756fa16108bcd7d806356d76c5ac2 to your computer and use it in GitHub Desktop.
Leetcode 114 - Flatten binary tree to list - a tough ride
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Leetcode114_FlattenBinaryTreeToLinkedList
{
/// <summary>
/// Leetcode 114 - Flatten binary tree to linked list
///
/// </summary>
class Program
{
static void Main(string[] args)
{
}
//Definition for a binary tree node.
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
}
public class Solution
{
public static void Flatten(TreeNode root)
{
if (root == null)
{
return;
}
bool hasLeftChild = root.left != null;
bool hasRightChild = root.right != null;
if (hasLeftChild)
{
var left = root.left;
Flatten(left);
}
if (hasRightChild)
{
var right = root.right; // added after failed online judge
Flatten(right);
// set left child to null
right.left = null;
}
if (hasLeftChild)
{
var left = root.left;
var end = getEnd(left);
var tmp = root.right;
root.right = left;
end.right = tmp;
// set left child to null
root.left = null; // set left child to null
}
}
/// <summary>
///
/// </summary>
/// <param name="root"></param>
public static TreeNode getEnd(TreeNode root)
{
bool hasRightChild = root.right != null;
if (hasRightChild)
{
return getEnd(root.right);
}
else
{
return root;
}
}
}
}
}
@jianminchen
Copy link
Author

A few mistakes in the first writing to pass online judge.

  1. Forget to flatten root.right children tree.
  2. It takes me more than 30 minutes to understand that the left child should set to null after it is flattened.
  3. Run into null pointer in the execution, so delay the root.left = null until line 65

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment