Leetcode 二叉树深度相关

44 阅读1分钟

104. 二叉树的最大深度

只学习了递归解决,后续遍历

class Solution {

public int maxDepth(TreeNode root) {

return getDepth(root);

  


}

private int getDepth(TreeNode root){

if(root==null)return 0;

  


int leftDepth = getDepth(root.left);

int rightDepth = getDepth(root.right);

int res = 1+Math.max(leftDepth,rightDepth);

return res;

  


}

}

111. 二叉树的最小深度

同递归,后续遍历

class Solution {

public int minDepth(TreeNode root) {

return getDepth(root);

}

private int getDepth(TreeNode root){

  


if(root==null)return 0;

  
  


int leftDepth = getDepth(root.left);

int rightDepth = getDepth(root.right);

  


if(root.left==null)return 1+rightDepth;

if(root.right==null)return 1+leftDepth;

int res = 1+Math.min(leftDepth,rightDepth);

return res;

}

}

222. 完全二叉树的节点个数

class Solution {

public int countNodes(TreeNode root) {

return num(root);

  


}

private int num(TreeNode root){

if(root==null)return 0;

  


int leftNum = num(root.left);

int rightNum = num(root.right);

  


int resNum = 1+leftNum+rightNum;

  


return resNum;

}

}