Skip to main content

Boundary of Binary Tree

LeetCode Link

Problem Description​

Visit LeetCode for the full problem description.


Solutions​

Solution 1: C# (Best: 244 ms)​

MetricValue
Runtime244 ms
Memory32.7 MB
Date2020-01-13
Solution
/**
* 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 IList<int> BoundaryOfBinaryTree(TreeNode root) {
List<int> result = new List<int>();
if(root == null) return result;
result.Add(root.val);
LeftBoundary(result, root.left);
Leaves(result, root.left);
Leaves(result, root.right);
RightBoundary(result, root.right);
return result;
}

void LeftBoundary(List<int> result, TreeNode root)
{
if(root == null || (root.left == null && root.right == null)) return;
result.Add(root.val);
if(root.left == null) LeftBoundary(result, root.right);
LeftBoundary(result, root.left);
}

void Leaves(List<int> result, TreeNode root)
{
if (root == null ) return;
if (root.left == null && root.right == null)
{
result.Add(root.val); return;
}
Leaves(result, root.left);
Leaves(result, root.right);
}

void RightBoundary(List<int> result, TreeNode root)
{
if (root == null || (root.left == null && root.right == null)) return;
if (root.right == null) RightBoundary(result, root.left);
RightBoundary(result, root.right);
result.Add(root.val);
}

}

Complexity Analysis​

ApproachTimeSpace
SolutionTo be analyzedTo be analyzed