算法与数据结构基础 - 二叉树(Binary Tree)

二叉树基础

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

二叉树是递归定义的,因而常用递归/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题:

104. Maximum Depth of Binary Tree  题解

112. Path Sum  题解

437. Path Sum III  题解

100. Same Tree  题解

543. Diameter of Binary Tree  题解

563. Binary Tree Tilt  题解

257. Binary Tree Paths  题解

671. Second Minimum Node In a Binary Tree  题解

572. Subtree of Another 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 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题:

94. Binary Tree Inorder Traversal  iterative题解  recursive题解

144. Binary Tree Preorder Traversal  iterative题解  recursive题解

145. Binary Tree Postorder Traversal  iterative题解

102. Binary Tree Level Order Traversal  题解

 

反过来,可以由中序、前序、后序序列构造二叉树。

 

相关LeetCode题:

889. Construct Binary Tree from Preorder and Postorder Traversal   题解

105. Construct Binary Tree from Preorder and Inorder Traversal  题解

106. Construct Binary Tree from Inorder and Postorder Traversal  题解

1028. Recover a Tree From Preorder Traversal   题解

536. Construct Binary Tree from String  题解 

297. Serialize and Deserialize Binary Tree   题解

 

除常见中序、前序、后序、层序遍历方式,还可以有各种花式遍历。

 

相关LeetCode题:

987. Vertical Order Traversal of a Binary Tree  题解

103. Binary Tree Zigzag Level Order Traversal  题解

545. Boundary of Binary Tree  题解
 

二叉树相关的问题,很多可以通过树的遍历求解。

 

相关LeetCode题:

965. Univalued Binary Tree  题解

872. Leaf-Similar Trees  题解

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

637. Average of Levels in Binary Tree  题解

226. Invert Binary Tree  题解

993. Cousins in Binary Tree  题解

101. Symmetric Tree  题解

111. Minimum Depth of Binary Tree  题解 

199. Binary Tree Right Side View  题解
 

树节点Ancestor

 

相关LeetCode题:

236. Lowest Common Ancestor of a Binary Tree  题解

1026. Maximum Difference Between Node and Ancestor  题解

1123. Lowest Common Ancestor of Deepest Leaves  题解

 
 

你可能感兴趣的:(算法与数据结构基础 - 二叉树(Binary Tree))