当前位置:网站首页>Leetcode-543- diameter of binary tree

Leetcode-543- diameter of binary tree

2022-06-21 23:31:00 z754916067

subject

 Insert picture description here

Ideas

  1. I don't think this will be done recursively … Sure enough, I haven't written the question for a long time , I have no idea about simple questions .
  2. Find out the diameter and length of each node as the root node, and then find the maximum value ? That's exactly the idea , Passed .

Code

    int ans=Integer.MIN_VALUE;
    public int diameterOfBinaryTree(TreeNode root) {
    
        if(root.left==null && root.right==null) return 0;
        // meaningless   Placeholder 
        int flag=DFS(root);
        return ans;

    }
    public int DFS(TreeNode root){
    
        // Take the current node as the root node   If you go to the leaf node   Note the diameter of the current node as the root node is 0  But take it as a side   Then return to 1
        if(root.left==null && root.right==null) return 1;
        // Otherwise, calculate 
        int leftval=0,rightval=0;
        if(root.left!=null)  leftval = DFS(root.left);
        if(root.right!=null) rightval = DFS(root.right);
        if(leftval+rightval>ans) {
    
            ans=leftval+rightval;
        }
        // Similarly, return the maximum value between two sides +1
        return Math.max(leftval,rightval)+1;
    }
原网站

版权声明
本文为[z754916067]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206212036272444.html

随机推荐