深度优先遍历包括:前中后序遍历
比较容易实现的是利用递归迭代进行遍历操作
前序遍历
public static void preOrderTree(Node root){
if(root==null){
return;
}
System.out.print(" "+root.val);
preOrderTree(root.left);
preOrderTree(root.right);
//时间复杂度为O(n)
中序遍历
public static void inOrderTree(Node root){
if(root==null){
return;
}
inOrderTree(root.left);
System.out.print(" "+root.val);
inOrderTree(root.right);
}
后序遍历
public static void postOrderTree(Node root){
if(root==null){
return;
}
postOrderTree(root.left);
postOrderTree(root.right);
System.out.print(" "+root.val);
}
关于二叉树的深度优先遍历的一些常见应用
//计算二叉树中节点的个数
public static int calcTreeNode(Node root){
if(root==null){
return 0;
}
count++;
calcTreeNode(root.left);
calcTreeNode(root.right);
return count;
}
public static int calcTreeNode_1(Node root){
if(root==null){
return 0;
}
int left=calcTreeNode_1(root.left);
int right=calcTreeNode_1(root.right);
return left+right;
}
//求二叉树的叶子结点个数
public static void cacLeafNode(Node root){
if(root==null){
return;
}
//代表结点 用来判断是否为叶子节点
if(root.left==null && root.right==null){
count++;
}
cacLeafNode(root.left);
cacLeafNode(root.right);
}
//求二叉树的高度
public static int calcHigh(Node root){
if(root==null){
return 0;
}
int left=calcHigh(root.left);
int right=calcHigh(root.right);
int height=Math.max(left,right);
return height+1;
}
//计算第k层的结点个数
public static int calcKlevel(Node root,int k){
if(root==null){
return 0;
}
if(k==1){
return 1;
}
int left=calcKlevel(root.left,k-1);
int right=calcKlevel(root.right,k-1);
int count=left+right;
return count;
}
1377

被折叠的 条评论
为什么被折叠?



