101. Symmetric Tree
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3]
is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3]
is not:
1
/ \
2 2
\ \
3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
Solution in C++:
- 关键点:递归中的处理部分和昨天的相同树差不多
- 思路:总体思路和相同树差不多,就是比较的子树的位置不一样,交换一下就可以了。
bool isSymme(TreeNode* left, TreeNode* right){
if (left == nullptr && right == nullptr)
return true;
else if(left == nullptr || right == nullptr)
return false;
if(left->val != right->val)
return false;
bool left_left = isSymme(left->left, right->right);
bool right_right = isSymme(left->right, right->left);
return left_left && right_right;
}
bool isSymmetric(TreeNode* root) {
if (root == nullptr)
return true;
else
return isSymme(root->left, root->right);
}
104. Maximum Depth of Binary Tree
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
return its depth = 3.
Solution in C++:
- 关键点:左右子树不可重复加
- 思路:开始打算用层次遍历的方法去做,但是后来发现好像递归就可以解决,每次扫描一层就加一。
int maxDepth(TreeNode* root) {
if (root == nullptr)
return 0;
else{
int llenth = maxDepth(root->left);
int rlenth = maxDepth(root->right);
if(rlenth >= llenth)
return rlenth + 1;
else
return llenth + 1;
}
}
小结
今天主要两个都是对于树的遍历问题的应用。一个是通过定义不同规则来判断结构问题,另一个是有点层次扫描的感觉。
- 树的遍历