Boundary of Binary Tree
Problem Descriptionβ
Visit LeetCode for the full problem description.
Solutionsβ
Solution 1: C# (Best: 244 ms)β
| Metric | Value |
|---|---|
| Runtime | 244 ms |
| Memory | 32.7 MB |
| Date | 2020-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β
| Approach | Time | Space |
|---|---|---|
| Solution | To be analyzed | To be analyzed |