forked from BigEggStudy/LeetCode-CS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1430-CheckIfAStringIsAValidSequenceFromRootToLeavesPathInABinaryTree.cs
47 lines (42 loc) · 1.66 KB
/
1430-CheckIfAStringIsAValidSequenceFromRootToLeavesPathInABinaryTree.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
//-----------------------------------------------------------------------------
// Runtime: 132ms
// Memory Usage: 36.1 MB
// Link: https://leetcode.com/submissions/detail/332559699/
//-----------------------------------------------------------------------------
namespace LeetCode
{
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class _1430_CheckIfAStringIsAValidSequenceFromRootToLeavesPathInABinaryTree
{
public bool IsValidSequence(TreeNode root, int[] arr)
{
return IsValidSequence(root, arr, 0);
}
private bool IsValidSequence(TreeNode root, int[] arr, int currentIndex)
{
if (root == null && currentIndex < arr.Length) return false;
if (root.val != arr[currentIndex]) return false;
if (currentIndex == arr.Length - 1)
return root.left == null && root.right == null;
if (root.left != null && root.right != null)
return IsValidSequence(root.left, arr, currentIndex + 1) || IsValidSequence(root.right, arr, currentIndex + 1);
else if (root.left != null)
return IsValidSequence(root.left, arr, currentIndex + 1);
else if (root.right != null)
return IsValidSequence(root.right, arr, currentIndex + 1);
return false;
}
}
}