递归实现最简单:当节点为null,则返回0;当节点不为空时,求孩子节点中,深度最大的那个值;最后返回孩子节点中,深度最大值+1。
方法一:递归法,枢机递归三部曲。第一步确定输入输出;第二步确定终止条件;第三步确定单层递归的逻辑
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
if(root==null) return 0;
//向左子树递归求深度
int leftDepth = maxDepth(root.left);
//向右子树递归求深度
int rightDepth = maxDepth(root.right);
return 1+( leftDepth>rightDepth?leftDepth:rightDepth);
}
}
方法二:
class solution {
/**
* 迭代法,使用层序遍历
*/
public int maxdepth(treenode root) {
if(root == null) {
return 0;
}
deque<treenode> deque = new linkedlist<>();
deque.offer(root);
int depth = 0;
while (!deque.isempty()) {
int size = deque.size();
depth++;
for (int i = 0; i < size; i++) {
treenode poll = deque.poll();
if (poll.left != null) {
deque.offer(poll.left);
}
if (poll.right != null) {
deque.offer(poll.right);
}
}
}
return depth;
}
}
/*
// Definition for a Node.
class Node {
public int val;
public List<Node> children;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, List<Node> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public int maxDepth(Node root) {
if(root == null) return 0;
int depth = 0;
for(Node node :root.children ){
depth = Math.max(depth,maxDepth(node));
}
return depth + 1;
}
}