算法與數據結構基礎 - 二叉樹(Binary Tree)

二叉樹基礎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

100. Same Tree  題解算法

543. Diameter of Binary Tree  題解數據結構

563. Binary Tree Tilt  題解ide

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,詳見:

算法與數據結構基礎 - 堆棧(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題:

872. Leaf-Similar Trees  題解

617. Merge Two Binary Trees  iterative題解  recursive題解

226. Invert Binary Tree  題解

相關文章
相關標籤/搜索