二叉树基础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题: