Leetcode 144 前序遍历
使用递归遍历。
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
stack<TreeNode*> stTree;
if(root == NULL) {return result;}
TreeNode* cur;
stTree.push(root);
while(!stTree.empty()){
cur = stTree.top();
stTree.pop();
result.push_back(cur -> val);
if(cur -> right != NULL) {stTree.push(cur -> right);}
if(cur -> left != NULL) {stTree.push(cur -> left);}
}
return result;
}
};
Leetcode 94 中序遍历
因为中序遍历实际节点的访问顺序与处理顺序(中序遍历顺序)并不相同,总是先访问中,而非左,因此需要用一个指针控制访问节点。
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<int> result;
if(root == NULL) {return result;}
TreeNode* cur = root;
while(cur != NULL || !st.empty()){
if(cur != NULL){
st.push(cur);
cur = cur -> left;
}
else{
cur = st.top();
st.pop();
result.push_back(cur -> val);
cur = cur -> right;
}
}
return result;
}
};
Leetcode 145 后序遍历
后序的顺序是左右中,可以先中右左,再翻转结果。
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<int> result;
if(root == NULL) {return result;}
st.push(root);
while(!st.empty()){
TreeNode* node = st.top();
st.pop();
result.push_back(node -> val);
if(node -> right) {st.push(node -> right);}
if(node -> left) {st.push(node -> left);}
}
reverse(result.begin(), result.end());
return result;
}
};
Leetcode 226 翻转二叉树
使用递归法,对一个root,翻转它的左右子节点,再翻转左右子树。递归问题需要明确函数参数及返回值,递归结束条件,单层递归的过程。
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root == NULL) return root;
swap(root -> left, root -> right);
invertTree(root -> left);
invertTree(root -> right);
return root;
}
};
Leetcode 101 对称二叉树
再次使用递归,相当于每次判断两棵对称子树的根是否相等;
class Solution {
public:
bool isRoot(TreeNode* L, TreeNode* R){
if(L != NULL && R == NULL) {return false;}
else if(L == NULL && R != NULL) {return false;}
else if(L == NULL && R == NULL) {return true;}
else if(L -> val != R -> val) {return false;}
bool outside = isRoot(L -> left, R -> right);
bool inside = isRoot(L -> right, R -> left);
return inside&&outside;
}
bool isSymmetric(TreeNode* root) {
if(root == NULL) return true;
return isRoot(root -> left, root -> right);
}
};