problem
Given a binary tree where each path going from the root to any leaf form a valid sequence, check if a given string is a valid sequence in such binary tree.
We get the given string from the concatenation(连接,拼接,并置) of an array of integers arr and the concatenation of all values of the nodes along a path results in a sequence in the given binary tree.
solution
方法
思路过程
先理解题意:
从根节点到叶结点才能算是一条有效的路径
特殊情况:只有根节点,只有一条路径,有多条路径
- 想法一:暴力,你可以遍历每一条路径,并记录每一条路径,然后比较
- 想法二,动态规划,和深度优先遍历,下一个数字能成立,当然是前一个数字也是在该路径中,记录每次走过的节点的值,
可能其中当前不等于相匹配的数字,回溯,遍历其他的节点;叶子的深度大于或小于路径了,回溯;直到找到叶子节点,并且路径中节点的个数与数组中相等,结束遍历
遍历过程中,堆栈结果不仅仅要记录节点的地址,也要记录当前节点的是深度的第几层
采用堆栈可能会好些,先序遍历完成
代码
python
class Solution:
def isValidSequence(self, root: TreeNode, arr) -> bool:
stack = []
length = len(arr)-1
# 有一个为空都是假
if root and arr:
# 初始化第一个值
if arr[0]==root.val:
stack.append([root, 0])
while stack:
node, position = stack.pop()
# if position > length:
# pass
# 这里已经检测到末尾的情况
if position == length:
# 这里就要检查是否相等和是否是叶子节点了
if node.val == arr[position] and node.left == None and node.right == None:
return True
if position < length:
# 还没有的话,在值符合的情况下就要继续往下走,
if node.val == arr[position]:
if node.right:
stack.append([node.right, position + 1])
if node.left:
stack.append([node.left, position + 1])
return False
java
class Solution {
public boolean isValidSequence(TreeNode root, int[] arr) {
int length = arr.length - 1;
// // 这里java的数据结构要好好考虑以下
//我是要顺序存储,并且还能存储两个信息,目前我还没有找到java提供的合适的数据结构
//就用两个栈同步吧
if (root != null && length >=0) {
Stack<TreeNode> nodes = new Stack<>();
Stack<Integer> positions = new Stack<>();
if (arr[0]==root.val){
nodes.push(root);
positions.push(0);
}
while (!nodes.isEmpty()){
TreeNode node=nodes.pop();
int position=positions.pop();
if (position==length){
if (node.val==arr[position] && node.left==null && node.right==null){
return true;
}
}
if (position<length && node.val==arr[position]){
if (node.left!=null){
nodes.push(node.left);
positions.push(position+1);
}
if (node.right!=null){
nodes.push(node.right);
positions.push(position+1);
}
}
}
}
return false;
}
}