创建二叉树上一篇中已经提到:https://blog.csdn.net/weixin_39309402/article/details/101349676
1、如何计算二叉树叶子节点(没有子结点[即度为0]的结点称为叶子结点,简称“叶子”)的个数
// 叶子节点的个数(递归算法)
public static int getNodeNumLeafRec(TreeNode root) {
if (root == null)
return 0;
if (root.left == null && root.left == null)
return 1;
return getNodeNumLeafRec(root.left) + getNodeNumLeafRec(root.right);
}
public static void main(String[] args) {
TreeNode root = new TreeNode();
root = createTree(root, 0);
System.out.println("叶子节点的个数:" + new Test2().getNodeNumLeafRec(root)); // 3
}
2、如何判断是否是二叉搜索树
/* 判断是否是二叉搜索树 */
// 方法一:计算高度
public int treedeep(TreeNode root) {
if (root == null)
return 0;
int left = treedeep(root.left);
int right = treedeep(root.right);
return Math.max(left, right) + 1;
}
public boolean QueryTree(TreeNode root) {
if (root == null)
return true;
int left = treedeep(root.left);
int right = treedeep(root.right);
if (Math.abs(right - left) > 1)
return false;
boolean treeleft = QueryTree(root.left);
boolean treeright = QueryTree(root.right);
return treeleft && treeright;
}
/**
* 验证二叉搜索树-方法二
*/
public boolean isvaild(TreeNode root) {
if (root == null) {
return true;
}
return valid(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
private boolean valid(TreeNode root, long minValue, long maxValue) {
if (root == null) {
return true;
}
if (root.val <= minValue || root.val >= maxValue) {
return false;
}
return valid(root.left, minValue, root.val) && valid(root.right, root.val, maxValue);
}
public static void main(String[] args) {
TreeNode root = new TreeNode();
root = createTree(root, 0);
System.out.println("判断是否是搜索二叉树:"+new Test2().QueryTree(root)); //false
System.out.println("判断是否是搜索二叉树:"+new Test2().isvaild(root)); //false
}
3、如何利用深度优先遍历二叉树?
// 深度优先遍历
public static void preorderTraversal(TreeNode root) {
if (root == null)
return;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
System.out.println(node.val);
if (null != node.left) {
stack.push(node.left);
}
if (null != node.right) {
stack.push(node.right);
}
}
}
public static void main(String[] args) {
TreeNode root = new TreeNode();
root = createTree(root, 0);
System.out.println("深度优先遍历二叉树:");
new Test2().preorderTraversal(root);
}