1. 某完全二叉树按层次输出(同一层从左到右)的序列为 ABCDEFGH 。该完全二叉树的前序序列为 ( )A: ABDHECFG B: ABCDEFGH C: HDBEAFCG D: HDEBFGCA2. 二叉树的先序遍历和中序遍历如下:先序遍历: EFHIGJK; 中序遍历: HFIEJKG. 则二叉树根结点为 ( )A: E B: F C: G D: H3. 设一课二叉树的中序遍历序列: badce ,后序遍历序列: bdeca ,则二叉树前序遍历序列为 ( )A: adbce B: decab C: debac D: abcde4. 某二叉树的后序遍历序列与中序遍历序列相同,均为 ABCDEF ,则按层次输出 ( 同一层从左到右 ) 的序列为 ()A: FEDCBA B: CBAFED C: DEFCBA D: ABCDEF【参考答案】 1.A 2.A 3.D 4.A
(3) 二叉树的基本操作
// 获取树中节点的个数int size ( Node root );// 获取叶子节点的个数int getLeafNodeCount ( Node root );// 获取第 K 层节点的个数int getKLevelNodeCount ( Node root , int k );// 获取二叉树的高度int getHeight ( Node root );// 检测值为 value 的元素是否存在Node find ( Node root , int val );// 层序遍历void levelOrder ( Node root );// 判断一棵树是不是完全二叉树boolean isCompleteTree ( Node root );
1.节点个数
//只要节点不为空,那么就count++
//只要节点不为空,那么就count++
public static int count=0;
public void size(TreeNode root) {
if(root==null){
return ;
}else{
count++;
size(root.left);
size(root.right);
}
}
//整棵树有多少个结点=左子树有多少个结点+右子树有多少个结点+1
public int size(TreeNode root) {
if(root==null){
return 0;
}
return size(root.left)+size(root.right)+1;
}
2.叶子节点的个数
//只要是叶子结点,那么就count++
public static int count=0;
public void getLeafNodeCount(TreeNode root){
if(root==null){
return ;
}
if(root.left==null&&root.right==null){
count++;
}
getLeafNodeCount(root.left);
getLeafNodeCount(root.right);
}
//整棵树有多少个叶子结点=左子树有多少个叶子结点+右子树有多少个叶子结点
public int getLeafNodeCount(TreeNode root){
if(root==null){
return 0;
}
if(root.left==null&&root.right==null){
return 1;
}
return getLeafNodeCount(root.left)+getLeafNodeCount(root.right);
}
3.第K层节点的个数
第k层结点个数=左子树的第k-1层结点个数+右子树的第k-1层结点个数
public int getKLevelNodeCount(TreeNode root,int k){
if(root==null){
return 0;
}
if(k==1){
return 1;
}
return getKLevelNodeCount(root.left,k-1)+getKLevelNodeCount(root.right,k-1);
}
4.二叉树的高度
二叉树的高度=左右子树高度的最大值+1
- 时间复杂度:O(N)
- 空间复杂度:O(logN)
public int maxDepth(TreeNode root) {
if(root==null){
return 0;
}
int leftHeight=maxDepth(root.left);
int rightHeight=maxDepth(root.right);
return Math.max(leftHeight,rightHeight)+1;
// return (leftHeight>rightHeight?leftHeight+1:rightHeight+1);
}
5.value的元素是否存在
如果根节点是则返回根节点,不是则向左子树遍历,左子树不是则向右子树遍历,左右子树都不是则返回空
- 时间复杂度:O(N)
- 空间复杂度:O(logN)
public TreeNode find(TreeNode root, int val){
if(root==null){
return null;
}
if(root.val==val){
return root;
}
TreeNode leftNode=find(root.left,val);
if(leftNode!=null){
return leftNode;
}
TreeNode rightNode=find(root.right,val);
if(rightNode!=null){
return rightNode;
}
return null;
}
6.层序遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> list=new ArrayList<>();
if(root==null){
return list;
}
TreeNode cur=root;
Queue<TreeNode> queue=new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
List<Integer> list2=new ArrayList<>();
int size=queue.size();
while(size>0){
cur=queue.poll();
list2.add(cur.val);
if(cur.left!=null){
queue.offer(cur.left);
}
if(cur.right!=null){
queue.offer(cur.right);
}
size--;
}
list.add(list2) ;
}
return list;
}
}
7.完全二叉树判断
利用队列,如果在弹出值为null时,查看当前queue内的值,如果全部是null则是完全二叉树,否则不是完全二叉树
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return bool布尔型
*/
public boolean isCompleteTree (TreeNode root) {
if(root==null){
return true;
}
Queue<TreeNode> queue=new LinkedList<>();
TreeNode cur=root;
queue.offer(root);
while(!queue.isEmpty()){
cur=queue.poll();
if(cur!=null){
queue.offer(cur.left);
queue.offer(cur.right);
}else{
break;
}
}
int size=queue.size();
while(size>0){
TreeNode now=queue.poll();
if(now!=null){
return false;
}
size--;
}
return true;
}
}
三、 二叉树相关oj题
1. 检查两颗树是否相同。
- 1.判断结构是否一样(左右子树要么同为空,要么同不为空)
- 2.左右子树同为null则正确
- 3.判断值是否一样
- 4.判断左子树,右子树是否一样
- 时间复杂度O(min(M,N))
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
//1.判断结构是否一样
if((p!=null&&q==null)||(p==null&&q!=null)){
return false;
}
//上述运行后通过的要么同为空,要么同不为空
//同为空则正确
if(p==null&&q==null){
return true;
}
//2.判断值是否一样
if(p.val!=q.val){
return false;
}
//3.判断左子树,右子树是否一样
return isSameTree(p.left, q.left)&&isSameTree(p.right, q.right);
}
}
2. 另一颗树的子树。
- 当前子树和根节点是否一样
- 当前子树和根节点左子树是否一样
- 当前子树和根节点右子树是否一样
- 时间复杂度O(M*N)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isSubtree(TreeNode root, TreeNode subRoot) {
if(root==null){
return false;
}
if(isSameTree(root, subRoot)){
return true;
}
if(isSubtree(root.left, subRoot)){
return true;
}
if(isSubtree(root.right, subRoot)){
return true;
}
return false;
}
public boolean isSameTree(TreeNode p, TreeNode q) {
//1.判断结构是否一样
if((p!=null&&q==null)||(p==null&&q!=null)){
return false;
}
//上述运行后通过的要么同为空,要么同不为空
//同为空则正确
if(p==null&&q==null){
return true;
}
//2.判断值是否一样
if(p.val!=q.val){
return false;
}
//3.判断左子树,右子树是否一样
return isSameTree(p.left, q.left)&&isSameTree(p.right, q.right);
}
}
3. 翻转二叉树。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root==null){
return null;
}
TreeNode tmp=root.left;
root.left=root.right;
root.right=tmp;
invertTree(root.left);
invertTree(root.right);
return root;
}
}
4. 判断一颗二叉树是否是平衡二叉树。
- 时间复杂度O(N^2)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isBalanced(TreeNode root) {
if(root==null){
return true;
}
int leftheight=getheight(root.left);
int rightheight=getheight(root.right);
return Math.abs(leftheight-rightheight)<2&&isBalanced(root.left)&&isBalanced(root.right);
/* if(Math.abs(leftheight-rightheight)>=2){
return false;
}
if(isBalanced(root.left)&&isBalanced(root.right)){
return true;
}
return false;*/
}
public int getheight(TreeNode root){
if(root==null){
return 0;
}
int leftheight=getheight(root.left);
int rightheight=getheight(root.right);
return Math.max(leftheight,rightheight)+1;
}
}
- 时间复杂度O(N)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isBalanced(TreeNode root) {
if(root==null){
return true;
}
return getheight(root)>=0;
}
public int getheight(TreeNode root){
if(root==null){
return 0;
}
int leftheight=getheight(root.left);
if(leftheight<0){
return -1;
}
int rightheight=getheight(root.right);
if(Math.abs(leftheight-rightheight)<=1&&rightheight>=0){
return Math.max(leftheight,rightheight)+1;
}else{
return -1;
}
}
}
5. 对称二叉树。
root的左子树和root的右子树是否对称
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
if(root==null){
return true;
}
return isSymmetricChild(root.left,root.right);
}
public boolean isSymmetricChild(TreeNode leftTree,TreeNode rightTree){
//判断结构一样
if((leftTree==null&&rightTree!=null)||(leftTree!=null&&rightTree==null)){
return false;
}
//左右同为空或者左右同不为空
if(leftTree==null&&rightTree==null){
return true;
}
if(leftTree.val!=rightTree.val){
return false;
}
return isSymmetricChild(leftTree.left,rightTree.right)&&isSymmetricChild(leftTree.right,rightTree.left);
}
}
6. 二叉搜索树和双向链表
二叉搜索树的特点:中序遍历是有序的
import java.util.*;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
TreeNode prev = null;
public TreeNode Convert(TreeNode pRootOfTree) {
if(pRootOfTree==null){
return null;
}
ConvertChild(pRootOfTree);
TreeNode head=pRootOfTree;
while(head.left!=null){
head=head.left;
}
return head;
}
public void ConvertChild(TreeNode root) {
if (root == null) {
return;
}
ConvertChild(root.left);
root.left = prev;
if (prev != null) {
prev.right = root;
}
prev = root;
ConvertChild(root.right);
}
}
7.二叉树的构建及遍历。
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
static class TreeNode{
public char val;
public TreeNode left;
public TreeNode right;
public TreeNode(char ch) {
this.val=ch;
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextLine()) { // 注意 while 处理多个 case
String str=in.nextLine();
TreeNode root= createTree(str);
Inorder(root);
}
}
public static int i=0;
public static TreeNode createTree(String str){
TreeNode root=null;
if(str.charAt(i)!='#'){
root=new TreeNode(str.charAt(i));
i++;
root.left=createTree(str);
root.right=createTree(str);
}else{
i++;
}
return root;
}
public static void Inorder(TreeNode root){
if(root==null){
return;
}
Inorder(root.left);
System.out.print(root.val+" ");
Inorder(root.right);
}
}
8. 二叉树的分层遍历 。
使用队列来辅助分层遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> list=new ArrayList<>();
if(root==null){
return list;
}
TreeNode cur=root;
Queue<TreeNode> queue=new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
List<Integer> list2=new ArrayList<>();
int size=queue.size();
while(size>0){
cur=queue.poll();
list2.add(cur.val);
if(cur.left!=null){
queue.offer(cur.left);
}
if(cur.right!=null){
queue.offer(cur.right);
}
size--;
}
list.add(list2) ;
}
return list;
}
}
9. 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先 。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root==null){
return null;
}
if(root==p||root==q){
return root;
}
TreeNode leftnode=lowestCommonAncestor(root.left, p, q);
TreeNode rightnode=lowestCommonAncestor(root.right, p, q);
if(leftnode==null){
return rightnode;
}else if(rightnode==null){
return leftnode;
}else{
return root;
}
}
}
利用前面的把二叉树改成双向链表的思路可以把距离父节点远的向父节点靠近
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root==null){
return null;
}
Stack<TreeNode> stackp=new Stack<>();
Stack<TreeNode> stackq=new Stack<>();
getPath(root,p,stackp);
getPath(root,q,stackq);
int sizep=stackp.size();
int sizeq=stackq.size();
int size=0;
if(sizep>sizeq){
size=sizep-sizeq;
while(size!=0){
stackp.pop();
size--;
}
}else{
size=sizeq-sizep;
while(size!=0){
stackq.pop();
size--;
}
}
while(!stackp.isEmpty()&&!stackq.isEmpty()){
if(stackp.peek()!=stackq.peek()){
stackp.pop();
stackq.pop();
}else{
return stackp.pop();
}
}
return null;
// if(root==null){
// return null;
// }
// if(root==p||root==q){
// return root;
// }
// TreeNode leftnode=lowestCommonAncestor(root.left, p, q);
// TreeNode rightnode=lowestCommonAncestor(root.right, p, q);
// if(leftnode==null){
// return rightnode;
// }else if(rightnode==null){
// return leftnode;
// }else{
// return root;
// }
}
public boolean getPath(TreeNode root,TreeNode p,Stack<TreeNode> stack){
if(root==null){
return false;
}
stack.push(root);
if(root==p){
return true;
}
boolean leftpath=getPath(root.left,p,stack);
if(leftpath){
return true;
}
boolean rightpath=getPath(root.right,p,stack);
if(rightpath){
return true;
}
stack.pop();
return false;
}
}
10. 根据一棵树的前序遍历与中序遍历构造二叉树。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int preIndex;
public TreeNode buildTree(int[] preorder, int[] inorder) {
return buildTreeChild(preorder, inorder,0,inorder.length-1);
}
public TreeNode buildTreeChild(int[] preorder,int[] inorder,int inBegin, int inEnd) {
//表示没有子树了
if(inBegin>inEnd){
return null;
}
TreeNode root=new TreeNode(preorder[preIndex]);//将首元素作为根节点
int midindex=findVal(inorder,inBegin,inEnd,preorder[preIndex]);
preIndex++;
root.left=buildTreeChild(preorder,inorder,inBegin,midindex-1);
root.right=buildTreeChild(preorder,inorder, midindex+1,inEnd);
return root;
}
private int findVal(int[] inorder,int inBegin, int inEnd,int val){
for(int i=inBegin;i<=inEnd;i++){
if(inorder[i]==val){
return i;
}
}
return -1;
}
}
11. 根据一棵树的中序遍历与后序遍历构造二叉树。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int postIndex;
public TreeNode buildTree(int[] inorder, int[] postorder) {
postIndex=postorder.length-1;
return buildTreeChild(inorder,postorder,0,inorder.length-1);
}
public TreeNode buildTreeChild(int[] inorder, int[] postorder,int inBegin,int inEnd) {
if(inBegin>inEnd){
return null;
}
TreeNode root=new TreeNode(postorder[postIndex]);
int findindex=findVal(inorder,inBegin,inEnd,postorder[postIndex]);
postIndex--;
root.right=buildTreeChild(inorder,postorder,findindex+1,inEnd);
root.left=buildTreeChild(inorder,postorder,inBegin,findindex-1);
return root;
}
private int findVal(int[] inorder,int inBegin,int inEnd,int val){
for(int i=inBegin;i<=inEnd;i++){
if(inorder[i]==val){
return i;
}
}
return -1;
}
}
12. 二叉树创建字符串。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public String tree2str(TreeNode root) {
StringBuilder stringBuilder =new StringBuilder();
tree2strChild(root,stringBuilder);
return stringBuilder.toString();
}
public void tree2strChild(TreeNode t,StringBuilder stringBuilder) {
if(t==null){
return;
}
stringBuilder.append(t.val);
if(t.left!=null){
stringBuilder.append('(');
tree2strChild(t.left,stringBuilder);
stringBuilder.append(')');
}else{
if(t.right==null){
return;
}else{
stringBuilder.append('(');
stringBuilder.append(')');
}
}
if(t.right!=null){
stringBuilder.append('(');
tree2strChild(t.right,stringBuilder);
stringBuilder.append(')');
}else{
return;
}
}
}
13. 二叉树前序非递归遍历实现
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list=new LinkedList<>();
Stack<TreeNode> stack=new Stack<>();
TreeNode cur=root;
while(cur!=null||!stack.isEmpty()){
while(cur!=null){
stack.push(cur);
list.add(cur.val);
cur=cur.left;
}
TreeNode top=stack.pop();
cur=top.right;
}
return list;
}
}
14. 二叉树中序非递归遍历实现。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list=new LinkedList<>();
Stack<TreeNode> stack=new Stack<>();
TreeNode cur=root;
while(cur!=null||!stack.isEmpty()){
while(cur!=null){
stack.push(cur);
cur=cur.left;
}
TreeNode top=stack.pop();
list.add(top.val);
cur=top.right;
}
return list;
}
}
15. 二叉树后序非递归遍历实现。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> list=new LinkedList<>();
Stack<TreeNode> stack=new Stack<>();
TreeNode cur=root;
while(cur!=null||!stack.isEmpty()){
while(cur!=null){
stack.push(cur);
cur=cur.left;
}
TreeNode top=stack.peek();
if(top.right==null||list.contains(top.right.val)){
top=stack.pop();
list.add(top.val);
}else{
cur=top.right;
}
}
return list;
}
}