Leetcode 543 Diameter of Binary Tree 笔记

250 阅读1分钟

Easy

思路

  • dfs
  • 建立长度为1的数组,用于在主函数和dfs函数中,传递更新最长diameter
  • base case: 当遍历到最底端是,节点为null时,返回0
  • sub: 左右子树
  • 判定最长D: back tracking时每到一个点检查当前节点左右子树之和是否是最长,
  • 之后返回两者较长的那个值给上一个

代码

class Solution {
    public int diameterOfBinaryTree(TreeNode root) {
        int[] res = new int[1];
        dfs(root, res);
        return res[0];
    }
    
    private int dfs(TreeNode root, int[] res){
        if(root == null) return 0;
        
        int left = dfs(root.left, res);
        int right = dfs(root.right, res);
        
        res[0] = Math.max(res[0], left + right);
        return Math.max(left, right) + 1;
    } 
}

07/25/20