package com.basic.bt;
import java.util.Stack;
/**
* 思路: 所谓计算个数,实际上是把每个结点遍历一遍
* (1)递归
* (2)非递归
*/
public class CountNodes {
int count = 0;
//inorder
public void countNodes(TreeNode root) {
if(root == null) {
return;
}
countNodes(root.left);
count++;
countNodes(root.right);
}
public void countPreOrder(TreeNode root) {
if(root == null) {
return;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
//当最后一个节点出栈时,就是遍历结束的时候,所有while循环里面不用判断 root是否为空,且root指针从未改变过。 中序遍历时需要主要
while(!stack.isEmpty()) {
TreeNode tmp = stack.pop();
count++;
if(tmp.right != null) {
stack.push(tmp.right);
}
if(tmp.left != null) {
stack.push(tmp.left);
}
}
}
//
public void countInOrder(TreeNode root) {
if(root == null) {
return;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
while(root != null || !stack.isEmpty()) {
while(root != null) {
stack.push(root);
root = root.left;
}
TreeNode node = stack.peek();
stack.pop();
count++;
root = node.right;
}
}
public void countPostOrder(TreeNode root) {
if(root == null) {
return;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode pre = null;
TreeNode node = root;
while(node != null || !stack.isEmpty()) {
if(node != null) {
stack.push(node);
node = node.left;
}
node = stack.pop();
count++;
while(node!= null && (node.right == null || node.right == pre)) {
count++;
pre = node;
//先判断是否为空,再pop 当只有最后一个节点的时候,本场景可以思考成功
if(stack.isEmpty()) {
return;
}
node = stack.pop();
}
count++;
stack.push(node);
node = node.right;
}
}
public static void main(String[] args) {
CountNodes test = new CountNodes();
TreeNode root = new TreeNode(0);
TreeNode node1 = new TreeNode(1);
TreeNode node2 = new TreeNode(2);
TreeNode node3 = new TreeNode(3);
TreeNode node4 = new TreeNode(4);
root.left = node1;
root.right = node2;
node1.left = node3;
node1.right =node4;
test.countPostOrder(root);
System.out.println("二叉树的结点个数为:" + test.count);
}
}
转载于:https://www.cnblogs.com/superzhaochao/p/6337386.html