二叉树
节点
public class TreeNode {
public int data;
public TreeNode left;
public TreeNode right;
public TreeNode(int data) {
this.data = data;
}
}
遍历
前序:根–>左–>右
中序:左–>根–>右
后序:左–>右–>根
前序遍历(递归)
public void preorderRecursion(TreeNode root){
if(root==null){
return;
}else{
System.out.print(root.data + " ");
preorderRecursion(root.left);
preorderRecursion(root.right);
}
}
前序遍历(非递归)
public void preorderTraversal(TreeNode root){
if(root==null)
return;
Stack<TreeNode> keep = new Stack<TreeNode>();
keep.push(root);
while(!keep.isEmpty()){
TreedNode node = keep.pop();
System.out.print(node.data + " ");
if(node.right!=null){
keep.push(node.right);
}
if(node.left!=null){
keep.push(node.left);
}
}
}
中序遍历(递归)
public void inorderRecursion(TreeNode root){
if(root==null){
return;
}else{
inorderRecursion(root.left);
System.out.print(root.data + " ");
inorderRecursion(root.right);
}
}
中序遍历(非递归)
public void inorderTraversal(TreeNode root){
if(root==null)
return;
Stack<TreeNode> keep = new Stack<TreeNode>();
TreeNode node = root;
while(!keep.isEmpty()||node!=null){
while(node!=null){
keep.push(node);
node = node.left;
}
node = keep.poll();
System.out.print(root.data + " ");
node=node.right;
}
}
后序遍历(递归)
public void postorderRecursion(TreeNode root){
if(root==null){
return;
}else{
postorderRecursion(root.left);
postordercursion(root.right);
System.out.print(root.data + " ");
}
}
后序遍历(非递归)
public static void postorderTraversal(TreeNode root){
if (root==null)
return;
Stack<TreeNode> keep = new Stack<TreeNode>();
Stack<TreeNode> keepNode = new Stack<TreeNode>();
TreeNode node = root;
while(node!=null||!keep.isEmpty()){
if (node!=null){
keep.push(node);
keepNode.push(node);
node=node.right;
}else {
node=keep.pop().left;
}
}
while (keepNode.size()>0) {
System.out.print(keepNode.pop().data+" ");
}
}
层序遍历+深度+节点个数、叶节点个数