二叉树节点路径求和
参考 https://www.nowcoder.com/questionTerminal/840dd2dc4fbd4b2199cd48f2dadf930a
另一种解法:
整体思路就是递归的去检索,每当经过一个节点的时候,就把节点值放入vector中,当到达叶子节点时,判断此时vector中的和是否等于给定sum,等于的话表示这是一条符合条件的路径,打印该路径。否则清空vector,继续检索。
https://blog.youkuaiyun.com/CHENYUFENG1991/article/details/5272335
二叉树深度
struct TreeNode{
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x):
val(x), left(NULL), right(NULL){
}
}
// depth
class Solution{
public:
int TreeDepth(TreeNode* pRoot){
if(pRoot == NULL)
return 0;
int left = TreeDepth(pRoot->left);
int right = TreeDepth(pRoot->right);
return (left>right?left:right)+1;
}
}
平衡二叉树
// is balanced binary tree
class Solution{
public:
bool IsBalancedSolution(TreeNode* pRoot){
if(pRoot == NULL)
return true;
if(TreeDepth(pRoot) == -1)
return false;
else
return true;
}
int TreeDepth(TreeNode* pRoot){
if(pRoot == NULL)
return 0;
int left = TreeDepth(pRoot->left);
if(left == -1)
return -1;
int right = TreeDepth(pRoot->right);
if(right == -1)
return -1;
if(left-right>1 || left-right<-1)
return -1;
else
return (left>right?left:right) + 1;
}
}
二叉树的遍历
前序、中序和后序都可以递归遍历,比较简单。
参考: https://www.cnblogs.com/gl-developer/p/7259251.html
https://blog.youkuaiyun.com/quzhongxin/article/details/46315251
https://www.cnblogs.com/llguanli/p/7363657.html
前序遍历
//前序遍历,压入顺序:右子树—>左子树->根节点
vector<int> preorder(TreeNode* root){
vector<int> result;
stack<TreeNode*> s;
if (root == NULL)
return result;
s.push(node);
while(!s.empty()){
TreeNode*p = s.top();
s.pop();
result.push_back(p->val);
if (p->right)
s.push(p->right);
if (p->left)
s.push(p->left);
}
return result;
}
中序遍历
// 中序遍历
vector<int> inorder(TreeNode* root){
vector<int> result;
stack<TreeNode*> s;
if (root == NULL)
return result;
TreeNode* p = root;
while(!s.empty() || p != NULL){
if (p != NULL){
// 左子树入栈
s.push(p);
p = p->left;
} else {
// 左子树为空时,访问该节点,然后访问右子树
p = s.top();
result.push_back(p->val);
s.pop();
p = p->right;
}
}
return result;
}
public static void inOrder(TreeNode root){
Stack<TreeNode> stack = new Stack<>();
TreeNode node = root;
while (node != null || stack.size() > 0) {
if (node != null){
stack.push(node);
node = node.left;
}
if (stack.size() > 0){
node = stack.pop();
visit(node);
node = node.right;
}
}
}
后序遍历
void postOrder2(BinTree *root){
stack<BTNode*> s;
BinTree *p = root;
BTNode *temp;
while(p!=NULL || !s.empty()){
while(p!=NULL){
BTNode btn = (BTNode *)malloc(sizeof(BTNode));
btn->btnode = p;
btn->isFirst = true;
s.push(btn);
p=p->lchild;
}
if(!s.empty()){
temp = s.top();
s.pop();
if(temp->isFirst==true){
temp->isFirst=false;
s.push(temp);
p=temp->btnode->rchild;
}
else{
cout<<temp->btnode->data<<" ";
p=NULL;
}
}
}
}
宽度遍历用队列。
双端队列deque,操作有back、push_back、front、pop_front、
队列queue,操作有push、pop、front
vector操作有pop_back、push_back
栈stack,操作有push、pop、top