二叉樹基礎css
知足這樣性質的樹稱爲二叉樹:空樹或節點最多有兩個子樹,稱爲左子樹、右子樹, 左右子樹節點一樣最多有兩個子樹。html
二叉樹是遞歸定義的,於是經常使用遞歸/DFS的思想處理二叉樹相關問題,例如LeetCode題目 104. Maximum Depth of Binary Tree:node
// 104. Maximum Depth of Binary Tree int maxDepth(TreeNode* root) { if(root==NULL) return 0; return 1+max(maxDepth(root->left),maxDepth(root->right)); }
相關LeetCode題:git
112. Path Sum 題解github
543. Diameter of Binary Tree 題解數據結構
671. Second Minimum Node In a Binary Tree 題解post
110. Balanced Binary Tree 題解spa
606. Construct String from Binary Tree 題解
樹的遍歷
除遞歸方式遍歷二叉樹外,另能夠藉助堆棧(stack)實現二叉樹中序、前序、後序遍歷,使用隊列(queue)實現按層遍歷,例如 LeetCode題目 94. Binary Tree Inorder Traversal:
// 94. Binary Tree Inorder Traversal vector<int> inorderTraversal(TreeNode* root) { vector<int> res; stack<TreeNode*> st; while(root || !st.empty()){ while(root){ st.push(root); root=root->left; } root=st.top();st.pop(); res.push_back(root->val); root=root->right; } return res; }
關於stack、queue,詳見:
相關LeetCode題:
144. Binary Tree Preorder Traversal iterative題解 recursive題解
102. Binary Tree Level Order Traversal 題解
反過來,能夠由中序、前序、後序序列構造二叉樹。
相關LeetCode題:
105. Construct Binary Tree from Preorder and Inorder Traversal 題解
106. Construct Binary Tree from Inorder and Postorder Traversal 題解
536. Construct Binary Tree from String 題解
除常見中序、前序、後序、層序遍歷方式,還能夠有各類花式遍歷。
相關LeetCode題:
103. Binary Tree Zigzag Level Order Traversal 題解
二叉樹相關的問題,不少能夠經過樹的遍歷求解。
相關LeetCode題: