104 Maximum Depth of Binary Tree

来源:互联网 发布:怎样安装电脑软件 编辑:程序博客网 时间:2024/05/17 07:46

题目链接:https://leetcode.com/problems/maximum-depth-of-binary-tree/

题目

Given a binary tree, find its maximum depth.The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

解题思路:
1、后序遍历(递归)
2、遍历到叶子节点时,返回1
3、遍历到分支节点时,比较左右子树的高度。返回 较大的子树高度 + 1

注意:
谨慎使用全局变量,会出现莫名其妙的错误,暂时还未查明其中原因。

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public int maxDepth(TreeNode root) {        int resL = 0;        int resR = 0;        if(root == null)            return 0;        if(root.left != null)            resL = maxDepth(root.left);        if(root.right != null)            resR = maxDepth(root.right);        if(root.left == null && root.right == null)            return 1;        int res = resL > resR ? resL : resR;        return res + 1;    }}
0 0
原创粉丝点击