这道题我用的层序遍历 ,把每一层的节点都放入栈中 然后反转它们的左右子树,
依次。
/**
* 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:
TreeNode* invertTree(TreeNode* root) {
stack<TreeNode*>st;
if(root == NULL) return root;
st.push(root);
while(!st.empty()){
TreeNode* node = st.top();
st.pop();
swap(node->left,node->right);
if(node->right) st.push(node->right); // 右
if(node->left) st.push(node->left);
}
return root;
}
};
这道题用递归 首先判断根节点的左右字数是否相等然后遍历(内部的和内部的比外部的和外部的比,然后判断它俩是不是都为true 如果是则返回true;
/**
* 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:
bool compare(TreeNode* left,TreeNode* right){
if(left ==NULL &&right !=NULL) return false;
else if (left !=NULL && right == NULL) return false;
else if (left ==NULL && right == NULL) return true;
else if( left->val != right->val) return false;
bool outside = compare(left->left,right->right);
bool inside = compare(left->right,right->left);
bool issame = outside && inside;
return issame;
}
bool isSymmetric(TreeNode* root) {
return compare(root->left,root->right);
}
};
其实深度是用后序遍历是比较舒服的因为判断完左右孩子的深度然后加一就是父节点的深度,
所以先递归到最后一个点然后依次把他们的值赋给父节点。
class Solution {
public:
int getDepth(TreeNode* node){
if (node ==NULL) return 0;
int leftDepth = getDepth(node->left);
int rightDepth = getDepth(node->right);
int depth = 1+max(leftDepth,rightDepth);
return depth;
}
int maxDepth(TreeNode* root) {
int depth = getDepth(root);
return depth;
}
};
这道题是找最小的叶子节点 如果为空则并不算深度 ,所以当遍历到空值的时候使用有值的数,
所以比最大值多了一个判定是否为叶子节点的过程。
class Solution {
public:
int getDepth(TreeNode* node){
if(node == NULL) return 0;
int leftDepth = getDepth(node->left);
int rightDepth = getDepth(node->right);
if(node->left == NULL && node->right !=NULL){
return 1+rightDepth;
}
else if(node->left!= NULL && node->right ==NULL){
return 1+leftDepth;
}
return 1+min(leftDepth,rightDepth);
}
int minDepth(TreeNode* root) {
int depth = getDepth(root);
return depth;
}
};