700. 二叉搜索树中的搜索https://leetcode-cn.com/problems/search-in-a-binary-search-tree/
给定二叉搜索树(BST)的根节点和一个值。 你需要在BST中找到节点值等于给定值的节点。 返回以该节点为根的子树。 如果节点不存在,则返回 NULL。
1、递归
//递归
public TreeNode searchBST1(TreeNode root,int val){
if(root==null||root.val==val){
return root;
}else if(val<root.val){
return searchBST(root.left,val);
}else{
return searchBST(root.right,val);
}
}
2、迭代
//迭代
public TreeNode searchBST(TreeNode root,int val){
//迭代 就是root节点的更新
while (root!=null){
if(root.val==val){
return root;
}
root=val>root.val?root.right:root.left;
}
return null;
}
104. 二叉树的最大深度https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
1、递归 DFS 深搜
//递归 深度优先搜索 DFS
public int maxDepth(TreeNode root){
if (root==null){
return 0;
}else {
int leftDepth=maxDepth(root.left);
int rightDepth=maxDepth(root.right);
return Math.max(leftDepth,rightDepth)+1;
}
}
2、广搜
101. 对称二叉树https://leetcode-cn.com/problems/symmetric-tree/
1、递归
//递归
public boolean isSymmetric(TreeNode root) {
return check1(root,root);
}
public boolean check1(TreeNode p,TreeNode q){
if(p==null&&q==null){
return true;
}
if(p==null||q==null){
return false;
}
return p.val==q.val&&check1(p.left,q.right)&&check1(q.left,p.right);
}
2、迭代
使用队列
//迭代
public boolean isSymmetric(TreeNode root){
return check(root,root);
}
public boolean check(TreeNode u,TreeNode v){
Queue<TreeNode> q=new LinkedList<TreeNode>();
q.offer(u);
q.offer(v);
while (!q.isEmpty()){
u=q.poll();
v=q.poll();
if(u==null&&v==null){
continue;
}
if((u==null||v==null)||(u.val!=v.val)){
return false;
}
q.offer(u.left);
q.offer(v.right);
q.offer(u.right);
q.offer(v.left);
}
return true;
}
nullhttps://leetcode-cn.com/problems/path-sum/
给你二叉树的根节点 root 和一个表示目标和的整数 targetSum 。判断该树中是否存在 根节点到叶子节点 的路径,这条路径上所有节点值相加等于目标和 targetSum 。如果存在,返回 true ;否则,返回 false 。
叶子节点 是指没有子节点的节点。
1、递归
//递归
public boolean hasPathSum1(TreeNode root,int targetSum){
if(root==null){
return false;
}
if(root.left==null&&root.right==null){
return root.val==targetSum;
}
return hasPathSum1(root.left,targetSum-root.val)||hasPathSum1(root.right,targetSum-root.val);
}
2、队列 广搜 层次遍历
//广搜 两个队列 层次遍历
public boolean hasPathSum(TreeNode root,int targetSum){
if(root==null){
return false;
}
//两个队列 一个存累计值 一个存节点
Queue<TreeNode> queueTree=new LinkedList<>();
Queue<Integer> queueVal=new LinkedList<>();
queueTree.offer(root);
queueVal.offer(root.val);
while (!queueTree.isEmpty()){
int size=queueTree.size();
for(int i=0;i<size;++i){
TreeNode node=queueTree.poll();
int val=queueVal.poll();
//必须是叶子节点
if(node.left==null&node.right==null){
if(val==targetSum){
return true;
}
}
if(node.left!=null){
queueTree.offer(node.left);
queueVal.offer(node.left.val+val);
}
if (node.right!=null){
queueTree.offer(node.right);
queueVal.offer(node.right.val+val);
}
}
}
return false;
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/path-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。