对于非递归二叉树遍历,深度遍历使用stack,宽度遍历使用queue。
模板:
stack<TreeNode *> st; // or queue<TreeNode *> q;
st.push(root);
TreeNode *t;
while(st.empty()){
t = st.top(); st.pop();
if(t){
st.push(t->left);
st.push(t->right);
}
}
一般,在宽度遍历或者深度遍历的时候,每个节点需要带一个状态。这时候,一般stack或者queue里就不只是TreeNode
可以使新建的struct,或者pair。记录深度或者记录path。比如。
struct AnnotateNode{
TreeNode *t;
vector<int> path;
int depth
};
对于递归遍历,简洁清晰,但是退出条件,以及相应的操作也要注意不要出错。比如翻转二叉树:
TreeNode* invertTree(TreeNode* root) {
if(!root) return root;
TreeNode *left = invertTree(root->left);
TreeNode *right = invertTree(root->right);
root->left = right;
root->right = left;
return root;
}
对于递归,有一种题目需要通道辅助的递归函数。比如判断是否平衡,需要左子树平衡,右子树平衡,并且左子树减右子树相差小于1。相关例子还有求二叉树的坡度(见leetcode)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int getsum(TreeNode *t){
if(!t) return 0;
return t->val + getsum(t->left) + getsum(t->right);
}
int findTilt(TreeNode* root) {
if(!root) return 0;
return findTilt(root->left) + findTilt(root->right) +
abs(getsum(root->left) - getsum(root->right));
}
};