數據結構-劍指offer-二叉樹的深度

題目:輸入一棵二叉樹,求該樹的深度。從根結點到葉結點依次經過的結點(含根、葉結點)形成樹的一條路徑,最長路徑的長度爲樹的深度。

思路:可以從根節點往下遍歷,每向下遍歷一個節點,深度加1,通過比較左右子樹的深度,獲得二叉樹的深度。因爲需要不斷比較左右深度,採用遞歸的方法或者迭代的方法:

方法一:(主要是參考了劍指offer,感覺自己對遞歸的理解還是不深刻)

class Solution {
public:
    int TreeDepth(TreeNode* pRoot)
    {
        if(pRoot == NULL)
            return NULL;
        int nLeft = TreeDepth(pRoot->left);
        int nRight = TreeDepth(pRoot->right);
        return (nLeft>nRight) ? (nLeft+1) : (nRight+1);
    }
};

方法二:也是遞歸,跟上面基本一致,只不過是在討論區看到的大神寫的最簡潔的代碼

class Solution {
public:
    int TreeDepth(TreeNode* pRoot)
    {
        if(pRoot == NULL) return 0;
        return max(TreeDepth(pRoot->left)+1, TreeDepth(pRoot->right)+1);
    }
};

方法三:迭代,層次遍歷思想。一次處理一層的數據。(掌握層次遍歷的思想!感覺很多題目都可以用層次遍歷實現!!!)

class Solution {
public:
    int TreeDepth(TreeNode* pRoot)
    {
        if(pRoot == NULL) return 0;
        queue<TreeNode*> que;
        que.push(pRoot);
        int depth = 0;
        while(!que.empty()){
            int size = que.size();
            depth ++;
            for(int i = 0; i< size;i++){
                TreeNode* node = que.front();
                que.pop();
                if(node->left){
                    que.push(node->left);
                }
                if(node->right){
                    que.push(node->right);
                }
            }
        }
        return depth;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章