1.前序遍历
void preOrderTraversal(Node root){
if(root==null) return;
System.out.print(root.val);
preOrderTraversal(root.left);
preOrderTraversal(root.right);
}
2.中序遍历
void inOrderTraversal(Node root){
if(root==null) return;
inOrderTraversal(root.left);
System.out.print(root.val);
inOrderTraversal(root.right);
}
3.后序遍历
void postrderTraversal(Node root){
if(root==null) return;
postOrderTraversal(root.left);
postOrderTraversal(root.right);
System.out.print(root.val);
}
4.遍历思路-求结点个数
static in size=0;
void getSize1(BTNode root){
if(root==null) return;
Size++;
getSize1(root.left);
getSize1(root.right);
}
5.子问题思路-求结点个数
左树+右树+1
int getSize2(BTNode root){
if(root==null) return 0;
getSize2(root.left)+getSize2(root.right)+1;
}
6.遍历思路-求叶子结点个数
static int leafSize=0;
void getLeafSize1(BTNode root){
if(root==null) return;
if(root.left==null&&root.right==null){
leafSize++;
}
getLeafSize1(root.left);
getLeafSize1(root.right);
}
7.子问题思路-求叶子结点个数
int getLeafSize2(BTNode root){
if(root==null) return 0;
if(root.left==null&&root.right.right){
return 1;
}
return getSize2(root.left)+getSize2(root.right);
}
8.子问题思路-求第k层结点个数
左数的第k-1层+右数的第k-1层
int getKLevelSize(BTNode root,int k){
if(root==null){
return 0;
}
if(k==1){
return 1;
}
return getKLevelSize(root.left,k-1)+getKLevelSize(root.right,k-1);
}
9.获取二叉树的高度
int getHeight(BTNode root){
if(root==null) return 0;
int leftHeight=getHeight(root.left);
int rightHeight=getHeight(root.right);
return leftHeight>rightHeight?
leftHeight+1:rightHeight+1;
}
10.查找val所在结点,没有找到返回null
BTNode find(BTNode root,char val){
if(root==null) return null;
if(root.val==val){
return root;
}
BTNode ret=find(root.left,val);
if(ret != null){
return ret;
}
BTNode ret=find(root.right,val);
if(ret != null){
return ret;
}
return null;
}