二叉树中的列表 Linked List in Binary Tree7
一颗以root
为根的二叉树,和一个head
为首节点的链表。如果在二叉树中存在一个一直向下的路径,并且每一个节点的值都对应head
为首节点的链表的值,那么就返回true
,否则返回 false
head = [4,2,8]
root =[1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]
true
思路
首先思考的是通过递归来解决,设计一个递归方法来处理。
方法主要用来判断树的节点tnode
和链表的节点lnode
向下寻找是否存在一条path
可以与lnode
节点开始的链表匹配。如果匹配就返回true,否则false。
接着就是递归的结束条件:
1 如果list已经匹配完了,那么就是存在的,true
2 如果tree都访问到null空节点,那么就不存在,false
3 如果节点对应的值不相等,false
4 如果不是上面的3种情况,说明目前来说匹配成功,那就继续递归。从tnode的左右子树,开始与lnode.next来匹配。
public boolean isSubPath(ListNode head, TreeNode root) {
if (head==null){
return true;
}
if (root == null){
return false;
}
if (head.val==root.val&&judge(root,head)){
return true;
}
return isSubPath(head,root.left)||isSubPath(head,root.right);
}
public boolean judge(TreeNode root,ListNode head){
if (head == null){
return true;
}
if (root == null){
return false;
}
if (head.val!=root.val){
return false;
}
return judge(root.left,head.next)||judge(root.right,head.next);
}
Tag
binary search