二叉树基础面试题(1)
数据结构部分看过一些面经觉得考的比较多的是排序,接着就是链表和二叉树部分了,今天联系了二叉树部分的一些面试题,就写写笔记啦~
1.二叉树的前序、中序、后续遍历
/**
* Created with IntelliJ IDEA
*
* @Description:
* @Author: zhen
* @Date: 2019/8/24
* @Time: 11:49
*/
public class TestBinaryTree {
class TreeNode{
char value;
TreeNode left;
TreeNode right;
public TreeNode(char value){
this.value = value;
}
}
//二叉树的前序遍历 --根左右
void binaryTreePrevOrder(TreeNode root){
if(root == null){
return;
}
System.out.print(root+"");
binaryTreePrevOrder(root.left);
binaryTreePrevOrder(root.right);
}
//中序遍历 左根右
void binaryTreeInOder(TreeNode root){
if(root == null){
return;
}
binaryTreeInOder(root.left);
System.out.print(root+"");
binaryTreeInOder(root.right);
}
//后序遍历 左右根
void binaryPostInOder(TreeNode root){
if(root == null){
return;
}
binaryPostInOder(root.left);
binaryPostInOder(root.right);
System.out.print(root+"");
}
}
2.二叉树的构建及遍历
public int i = 0;
TreeNode createTestTree(String s){
TreeNode root = null;
if(s.charAt(i) != '#'){
//根节点
root = new TreeNode(s.charAt(i));
i++;
root.left = createTestTree(s);
root.right=createTestTree(s);
}else{
i++;
}
return root;
}
3.求节点个数
public int getSize(TreeNode root){
if(root == null){
return 0;
}
return getSize(root.right)+getSize(root.left)+1;
}
4.求叶子节点
public int getLeafSize(TreeNode root){
if(root == null){
return 0;
}
//左右孩子都为null则为叶子结点
if(root.left == null && root.right == null){
return 1;
}
return getLeafSize(root.left)+getLeafSize(root.right);
}
5.求第k层节点个数
public int getKSize(TreeNode root,int k){
if(root == null){
return 0;
}else if(k == 1){
return 1;
}
return getKSize(root.right,k-1)+getKSize(root.left,k-1);
}
6.查找,依次在二叉树的 根、左子树、右子树 中查找 value,如果找到,返回结点,否则返回 null
TreeNode find(TreeNode root,char value){
if(root == null){
return null;
}
if(root.value == value){
return root;
}
//在root的左边 查找是否有该值
TreeNode ret = find(root.left,value);
if(ret != null){
return ret;
}
//如果左边没有,再在右边查找
ret = find(root.right,value);
if(ret != null){
return ret;
}
//如果两边都没有找到返回null
return null;
}
7.二叉树的高度
int Treeheight(TreeNode root){
if(root == null){
return 0;
}else{
int lefthight = Treeheight(root.left);
int righthigh = Treeheight(root.right);
return lefthight > righthigh?lefthight+1:righthigh+1;
}
}