//DFS解法 前序遍历 /** * 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 rightDepth = maxDepth(root.right); int leftDepth = maxDepth(root.left); return 1 + max(rightDepth,leftDepth); } public int max(int rightDepth, int leftDepth) { return rightDepth > leftDepth ? rightDepth :leftDepth; } } //BFS解法 层次遍历 /** * 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;} Queue<TreeNode> que = new LinkedList<>(); que.offer(root); int depth = 0; while (!que.isEmpty()){ int len = que.size(); depth ++; for (int i = 0; i < len; i++) { TreeNode node = que.poll(); if(node.left != null) { que.offer(node.left); } if(node.right != null) { que.offer(node.right); } } } return depth; } }
标签:node,right,TreeNode,val,int,Leecode104,二叉树,深度,left From: https://www.cnblogs.com/noedaydayup/p/16776908.html