[DS] 3. 二叉樹(Binary Tree)

1 · Rain Hu · Oct. 6, 2022, 3 p.m.
一、二叉樹的思維模式 二叉樹的解題模式大致分為兩類: 是否可以通過遍歷一遍得解 是否可以定義一個遞迴函數,通過分治法推導出原問題的答案? [LeetCode. 104] Maximum Depth of Binary Tree(Easy) 以此題為例,可以遍歷完整個樹,並比較當下的樹的深度,得以求解。 int depth = 0; int maxDepth(TreeNode* root){ traverse(root, 1); return depth; } void traverse(TreeNode* root, int currDepth){ if (!root) return; traverse(root->left, currDepth+1); depth = max(depth, currDepth); traverse(root->right, currDepth+1); } 若想辦法定義一個遞迴函數,通過分治法推導出原問題,換言之,就是先處理更小的樹,再藉由小的樹處理大的樹: int maxDepth(TreeNode* root) { if (root == NULL...