Created
June 22, 2017 21:45
-
-
Save jianminchen/83f756fa16108bcd7d806356d76c5ac2 to your computer and use it in GitHub Desktop.
Leetcode 114 - Flatten binary tree to list - a tough ride
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A few mistakes in the first writing to pass online judge.