java with depth of left subtree and right subtree 27ms


  • 0
    S
    // find the maxDepth of left subTree and the maxDepth of right subTree
    public class Solution {
        public int diameterOfBinaryTree(TreeNode root) {
            if(root == null){
                return 0;
            }
            int maxAns = 0;
            // traverse every node
            Stack<TreeNode> stack = new Stack<TreeNode>();
            stack.push(root);
            while (!stack.empty()) {
                TreeNode node = stack.pop();
                int temp = maxDepth(node.left) + maxDepth(node.right);
                maxAns = maxAns > temp? maxAns: temp;
                if (node.right != null) {
                    stack.push(node.right);
                }
                if (node.left != null) {
                    stack.push(node.left);
                }
            }
            return maxAns;
        }
        
        public int maxDepth(TreeNode root){
            if(root == null){
                return 0;
            }
            return Math.max(maxDepth(root.left), maxDepth(root.right) ) + 1;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.