非递归算法求二叉树节点个数
时间: 2023-06-18 17:08:47 浏览: 102
非递归算法求二叉树节点个数可以使用层序遍历的方式,也叫广度优先搜索。具体步骤如下:
1. 新建一个队列,将根节点入队。
2. 当队列不为空时,取出队列头部的节点,将其左右子节点入队。
3. 对每个出队节点计数。
4. 遍历完整棵树后,返回节点数。
下面是Python实现代码:
```python
def count_nodes(root):
if not root:
return 0
count = 0
queue = [root]
while queue:
node = queue.pop(0)
count += 1
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return count
```
时间复杂度为$O(n)$,空间复杂度为$O(w)$,其中$w$是二叉树的宽度,即最大的一层节点数。
相关问题
非递归算法求二叉树的叶结点个数C++
可以使用迭代法(非递归算法)来求解二叉树的叶结点个数,具体思路如下:
1.定义一个计数器 count,初始化为0。
2.使用栈来遍历二叉树。首先将根节点入栈。
3.进入循环,当栈不为空时执行以下操作:
- 弹出栈顶元素,如果该元素为叶结点,则将 count 加1。
- 如果该元素有右子树,则将右子树入栈。
- 如果该元素有左子树,则将左子树入栈。
4.遍历结束后,返回 count 值即可。
下面是C++代码实现:
```c++
int countLeaves(TreeNode* root) {
if (!root) {
return 0;
}
int count = 0;
stack<TreeNode*> st;
st.push(root);
while (!st.empty()) {
TreeNode* node = st.top();
st.pop();
if (!node->left && !node->right) {
count++;
}
if (node->right) {
st.push(node->right);
}
if (node->left) {
st.push(node->left);
}
}
return count;
}
```
其中,TreeNode 表示二叉树的节点。
用非递归算法求二叉树的叶结点个数c
可以使用迭代法(非递归)实现二叉树的叶子节点个数。具体步骤如下:
1. 定义一个栈来存储节点指针。
2. 从根节点开始,将根节点指针入栈。
3. 循环遍历栈中的节点指针,如果该节点是叶子节点,则叶子节点个数加1;否则,将该节点的左右子节点指针分别入栈。
4. 直到栈为空,遍历结束,返回叶子节点个数。
以下是C++代码实现:
```c++
int countLeafNode(TreeNode* root) {
if (root == nullptr) return 0;
stack<TreeNode*> st;
st.push(root);
int count = 0;
while (!st.empty()) {
TreeNode* cur = st.top();
st.pop();
if (cur->left == nullptr && cur->right == nullptr) {
count++;
} else {
if (cur->left) st.push(cur->left);
if (cur->right) st.push(cur->right);
}
}
return count;
}
```
注:这里假设树节点的定义为 `TreeNode`,包含 `left` 和 `right` 分别表示左右子节点的指针。