Binary Tree Level Order Traversal
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree {3,9,20,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
class Solution { public: vector<vector<int> > levelOrder(TreeNode *root) { vector<vector<int> > result; queue<TreeNode*> nodeLevel; queue<TreeNode*> newNodeLevel; vector<int> nodeVec; if(root){ nodeLevel.push(root); while(!nodeLevel.empty()){ nodeVec.clear(); while(!nodeLevel.empty()){ TreeNode* node = nodeLevel.front(); nodeLevel.pop(); nodeVec.push_back(node->val); if(node->left){ newNodeLevel.push(node->left); } if(node->right){ newNodeLevel.push(node->right); } } if(!nodeVec.empty()){ result.push_back(nodeVec); } nodeLevel.swap(newNodeLevel); } } return result; } };
2、Symmetric Tree
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following is not:
1 / \ 2 2 \ \ 3 3
分析:对于二叉树一般采用递归的方法,判断是否是镜像映射,可以采用判断对应的左子树是否和右子树相同的方法来进行判断。
class Solution { public: bool isSymmetric(TreeNode *root) { if(!root){ return true; } return isSame(root->left,root->right); } bool isSame(TreeNode* root1, TreeNode* root2){ if(!root1 && !root2){ return true; } if(root1 && root2){ if(root1->val != root2->val){ return false; } bool isLeft = isSame(root1->left,root2->right); bool isRight = isSame(root1->right,root2->left); if(isLeft && isRight){ return true; } } return false; } };
3、Same Tree
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
class Solution { public: bool isSameTree(TreeNode *p, TreeNode *q) { if(!p && !q){ return true; } if(p && q){ if(p->val != q->val){ return false; } bool isLeft = isSameTree(p->left,q->left); bool isRight = isSameTree(p->right,q->right); if(isLeft && isRight){ return true; } } return false; } };