145.二叉树的后序遍历
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void houxu(TreeNode*root,vector<int>&res){//这里注意是&不是*
if(root==nullptr) return;
houxu(root->left,res);
houxu(root->right,res);
res.push_back(root->val);
}
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
houxu(root,res);
return res;
}
};
剑指 Offer 32 - III 从上到下打印二叉树 III
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
if (root == nullptr)
{
return res;
}
queue<TreeNode*> q;
q.push(root);
while (!q.empty())
{
vector<int> currs;
for (int i = q.size() - 1; i >= 0; --i)
{
TreeNode* curr = q.front();
q.pop();
currs.push_back(curr->val);
if (curr->left)
{
q.push(curr->left);
}
if (curr->right)
{
q.push(curr->right);
}
}
// 当前res.size()为偶数时无需翻转,否则要翻转
if (res.size() & 1)//i & 1 可以判断 i 奇偶 ,i & 1 == 0 偶数
{
reverse(currs.begin(), currs.end());//reverse()反转vector
}
res.push_back(currs);
}
return res;
}
};
面试题55 - I. 二叉树的深度
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root: return 0#这里ruturn的是0
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
#这个+1导致return的结果能是它的遍历深度
剑指 Offer 28. 对称的二叉树
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
def recur(l,r):
if not l and not r:return True
if not l or not r or l.val!=r.val:return False#复合l和r之间有一个有值,或者都有值但是值不相等
return recur(l.left,r.right) and recur(l.right,r.left)
return recur(root.left,root.right) if root else True
剑指 Offer 26. 树的子结构
class Solution:
def isSubStructure(self, A: TreeNode, B: TreeNode) -> bool:
if not A or not B:return False
def recur(a,b):
if not b:#b遍历完了,为正
return True
if not a or a.val!=b.val:#a遍历完了b没有或者val不相同,为False
return False
return recur(a.right,b.right) and recur(a.left,b.left)
return recur(A,B) or self.isSubStructure(A.left,B) or self.isSubStructure(A.right,B)
双重递归题:A与B的可能性:1.A和B在根节点重recur(A,B)为True 2.B是A的子节点子结构 3.B是A的右节点子结构
如果AB为空树,返回False.