算法与数据结构基础

二叉树基础

满足这样性质的树称为二叉树:空树或节点最多有两个子树,称为左子树、右子树, 左右子树节点同样最多有两个子树。

二叉树是递归定义的,因而常用递归/DFS的思想处理二叉树相关问题,例如LeetCode题目 104. Maximum Depth of Binary Tree:

    // 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题:

112. Path Sum  题解

100. Same Tree  题解

543. Diameter of Binary Tree  题解

563. Binary Tree Tilt  题解

671. Second Minimum Node In a Binary Tree  题解

110. Balanced Binary Tree  题解

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  题解

 
 
原文地址:https://www.cnblogs.com/bangerlee/p/11269688.html