leetcode-MaxDepth of a binaryTree

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.

兩種遞歸:

    int maxDepth(TreeNode* root) {
       if(root==NULL)
        return 0;
        int leftmax=maxDepth(root->left)+1;
        int rightmax=maxDepth(root->right)+1;
        return leftmax>=rightmax?leftmax:rightmax; 
    }
    i
    nt maxDepth(TreeNode* root) {
         if(root==NULL)
        return 0;
        int leftmax=0,rightmax=0;

        if(!root->left&&!root->right) //leaf node
        return 1;

        if(root->left&&root->right)  { // two sons
            leftmax=maxDepth(root->left);
            rightmax=maxDepth(root->right);
            return leftmax>rightmax?(leftmax+1):(rightmax+1);
        }
        if(root->left){//only left son
            return maxDepth(root->left)+1;
        }
        if(root->right){//only right son
            return maxDepth(root->right)+1;
        }

        return 0;// control reaches end of non-void function [-Werror=return-type] 
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章