C++刷題筆記:樹


求樹的深度

struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};

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

判斷平衡二叉樹

輸入一棵二叉樹,判斷該二叉樹是否是平衡二叉樹。在這裏,我們只需要考慮其平衡性,不需要考慮其是不是排序二叉樹。

class Solution {
public:
    int depth(TreeNode *root) {
        if (!root) return 0;		// 空樹也是平衡樹
        
        int l = depth(root->left);   // 提前截止
        if (l == -1) return -1;
        
        int r = depth(root->right);  // 提前截止
        if (r == -1) return -1;
        
        if (abs(l - r)> 1) return -1;
        return max(l, r) + 1;
    }
    bool IsBalanced_Solution(TreeNode* root) {
        return depth(root) != -1;
    }
};

重建二叉樹

輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。

思路:

  • 遞歸截止:子樹序列中無結點
  • 由前序序列確定根結點
  • 在中序序列中根據root的索引,分爲左右子樹
  • 分別遞歸左子樹和右子樹
  • 返回根節點
    在這裏插入圖片描述
class Solution {
public:
    TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
        // 遞歸求解
        return reconstruct(pre, 0, pre.size(), vin, 0, vin.size());
    }
    
    TreeNode* reconstruct(vector<int>& pre, int pl, int pr, 
                          vector<int>& vin, int vl, int vr){
        // 前序沒有結點時,迭代終止
        if(pl==pr) return nullptr;
        // 根節點
        TreeNode* root = new TreeNode(pre[pl]);
        // 確定中序遍歷中根節點的索引,分爲左右子樹,進行遞歸
        for(int i=vl; i<vr; ++i){
            if(vin[i] == root->val){
                int num = i - vl; // 左子樹的結點個數
                root->left = reconstruct(pre, pl+1, pl+1+num, vin, vl, i);
                root->right = reconstruct(pre, pl+1+num, pr, vin, i+1, vr);
                break;
            }
        }
        return root;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章