赞
踩
int count = 0; int size(TreeNode root){ if (root == null){ return 0; } count++; return size(root.left)+size(root.right); } /** * 子问题思路 */ int size1(TreeNode root){ if (root == null) return 0; //左子树和右子树之和+根节点 return size1(root.left)+size1(root.right)+1; }
int leafCount = 0;
void getLeafNodeCount(TreeNode root){
if(root == null){
return;
}
//左子树和右子树都为null时,是叶子结点
if (root.left == null && root.right ==null){
leafCount++;
}
//递归左子树和右子树
getLeafNodeCount(root.left);
getLeafNodeCount(root.right);
int leafCount1 = 0;
int getLeafNodeCount1(TreeNode root) {
if (root == null) {
return 0;
}
if (root.left == null &&root.right == null){
//当前的root没有子树,自己就是叶子节点
return 1;
}
return getLeafNodeCount1(root.left) + getLeafNodeCount1(root.right);
}
public int getKLevelNodeCount(TreeNode root,int k){
if (root == null || k <= 0){
return 0;
}
if (k == 1){
//当k=1时,第一层
return 1;
}
//k不为1时:递归
return getKLevelNodeCount(root.left,k-1) + getKLevelNodeCount(root.right,k-1);
}
int getHeight2(TreeNode root) { if(root == null){ return 0; } int leftHeight = getHeight2(root.left); int rightHeight = getHeight2(root.right); return leftHeight>=rightHeight ? leftHeight+1 : rightHeight+1; } int getHeight(TreeNode root){ if(root == null){ return 0; } //比较左树高度和右树高度,取最大值 int leftHeight = getHeight(root.left); int rightHeight = getHeight(root.right); return leftHeight > rightHeight ? leftHeight+1 : rightHeight+1; //return getHeight(root.left) > getHeight(root.right)? (getHeight(root.left)+1):(getHeight(root.right)+1); //递归的次数太多了,重复计算了好多次,err //超出规定的运行时间:1.死循环 2.递归的次数太多了 }
TreeNode find(TreeNode root,char val) { if (root == null) return null; if (root.val == val){ return root; } TreeNode ret = find(root.left,val); if(ret!=null){ return ret; } ret = find(root.right,val); //如果左子树没有值为value的元素,看看右子树 if (ret != null){ return ret; } return null; }
{ if(root == null){ return true; } //队列 Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root);//将根入队列 //循环 while (!queue.isEmpty()){ // 队列不为空 TreeNode cur = queue.poll(); //取出队头元素给cur if (cur != null){ //当取出的队头不为null时,加入其左子树和右子树两个元素 queue.offer(cur.left); queue.offer(cur.right); }else { break; //为null时,中止循环 } } //看队列剩下的元素是否都为null,如果有不为null的元素,那么就不是完全二叉树 while(!queue.isEmpty()){ TreeNode top = queue.peek(); if(top != null){ return false; } queue.poll(); } return true; }
时间复杂度:O(min(M,N))
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p == null && q == null){
//
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。