publicintTreeDepth(TreeNode root){if(root == null)return0;//递归求左子树的深度int left =TreeDepth(root.left);//递归求右子树的深度int right =TreeDepth(root.right);//返回当前节点为根节点的子树的深度return Math.max(left,right)+1;}
publicbooleanHasSubtree(TreeNode root1,TreeNode root2){//输入参数合法性校验if(root1 == null || root2 == null)returnfalse;boolean result =false;//当前节点与二叉树B根节点相等,进行子树递归判断if(root1.val == root2.val)
result =isSubtree(root1.left,root2.left)&&isSubtree(root1.right,root2.right);//当前节点与二叉树节点不相等,遍历左子树if(!result)
result =HasSubtree(root1.left,root2);//当前节点的左子树中没有二叉树B的结构,遍历右子树if(!result)
result =HasSubtree(root1.right,root2);return result;}//递归子树查找二叉树B是否存在privatebooleanisSubtree(TreeNode root1,TreeNode root2){//如果二叉树B走到null,说明这条支路是符合的if(root2 == null)returntrue;//如果还没走完当前分支,继续比较if(root1 != null)if(root1.val == root2.val)returnisSubtree(root1.left,root2.left)&&isSubtree(root1.right,root2.right);returnfalse;}
层序遍历二叉树(BFS-队列)
public ArrayList<Integer>PrintFromTopToBottom(TreeNode root){//返回的层序遍历结果
ArrayList<Integer> result =newArrayList<>();if(root == null)return result;//根据层序遍历的特点符合队列的先进先出,使用队列作为中间容器,存放每一层的元素
Queue<TreeNode> queue =newLinkedList<>();
queue.offer(root);while(!queue.isEmpty()){//记录每一层的非空节点数目int size = queue.size();//遍历记录节点的值,并存储下一层的非空节点for(int i =0; i < size; i++){
TreeNode cur = queue.poll();
result.add(cur.val);if(cur.left != null)
queue.offer(cur.left);if(cur.right != null){
queue.offer(cur.right);}}}return result;}
之字形遍历二叉树(栈)
public ArrayList<ArrayList<Integer>>Print(TreeNode root){//返回结果
ArrayList<ArrayList<Integer>> result =newArrayList<>();if(root == null)return result;//当前层的节点栈
Stack<TreeNode> cur =newStack<>();
cur.push(root);//标志子节点入队方向boolean flag =true;while(!cur.isEmpty()){//当前层的节点个数int size = cur.size();//存放当前层的遍历结果
ArrayList<Integer> temp =newArrayList<>();//下一层的节点栈
Stack<TreeNode> next =newStack<>();//从左向右入栈子节点if(flag){for(int i =0; i < size; i++){
TreeNode current = cur.pop();
temp.add(current.val);if(current.left != null)
next.push(current.left);if(current.right != null)
next.push(current.right);}//从右向左入栈子节点}else{for(int i =0; i < size; i++){
TreeNode current = cur.pop();
temp.add(current.val);if(current.right != null)
next.push(current.right);if(current.left != null)
next.push(current.left);}}//更新子节点入栈顺序
flag =!flag;//添加当前层的遍历结果
result.add(temp);//更新下一次处理的节点栈
cur = next;}return result;}
public ArrayList PrintFromTopToBottom(TreeNode root) {//返回的层序遍历结果ArrayList result = new ArrayList&amp;amp;amp;amp;amp;lt;&amp;amp;amp;amp;amp;gt;();if(root == null)return result;//根据层序遍历的特点符合队列的先进先出,使用队列作为中间容器,存放每一层的元素Queue queue = ne..