LC美版30天挑战的一道题,没有中文。题意是给一个二叉树和一个从根节点开始的sequence,请你判断这个sequence是否是一个有效的,从根节点到某个叶子节点的sequence。例子,
Input: root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,1,0,1] Output: true Explanation: The path 0 -> 1 -> 0 -> 1 is a valid sequence (green color in the figure). Other valid sequences are: 0 -> 1 -> 1 -> 0 0 -> 0 -> 0
我只放一个例子好了,因为这个题比较直观。如果给出的sequence arr少任何一个节点,都要return false。
思路是DFS深度遍历。如果遍历到的当前节点没有左孩子也没有右孩子,说明是叶子节点了,则判断其val是否等于arr的最后一个节点的val;接着去递归遍历其左子树和右子树,同时记得判断当前节点是否等于arr中对应index上的val。
时间O(n)
空间O(n)
Java实现
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode() {} 8 * TreeNode(int val) { this.val = val; } 9 * TreeNode(int val, TreeNode left, TreeNode right) { 10 * this.val = val; 11 * this.left = left; 12 * this.right = right; 13 * } 14 * } 15 */ 16 class Solution { 17 public boolean isValidSequence(TreeNode root, int[] arr) { 18 return dfs(root, arr, 0); 19 } 20 21 private boolean dfs(TreeNode root, int[] arr, int index) { 22 if (root.left == null && root.right == null && root.val == arr[index] && index == arr.length - 1) { 23 return true; 24 } 25 return root.val == arr[index] && (dfs(root.left, arr, index + 1) || dfs(root.right, arr, index + 1)); 26 } 27 }