二叉樹遍歷七種方式
阿新 • • 發佈:2018-12-10
數結構
public class TreeNode {
public TreeNode left;
public TreeNode right;
int val;
...
}
先序(遞迴)
public void preOrder(TreeNode root){
if(root != null){
System.out.println(root.getVal());
preOrder(root.getLeft());
preOrder(root.getRight());
}
}
先序(非遞迴)
public void preOrder(TreeNode root){ Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode p = root; while(!stack.isEmpty() || p != null){ while(p != null){ System.out.println(root.getVal()); stack.push(p); p = p.getLeft(); } if(!stack.isEmpty()){ TreeNode pTemp = stack.pop(); p = pTemp.getRight(); } } }
中序(遞迴)
public void inOrder(TreeNode root){
if(root != null){
inOrder(root.getLeft());
System.out.println(root.getVal());
inOrder(root.getRight());
}
}
中序(非遞迴)
public void inOrder(TreeNode root){ Stack<TreeNode> stack = new Stack<TreeNode>(); while(!stack.isEmpty() || root != null){ while(root != null){ stack.push(root); root = root.getLeft(); } if(!stack.isEmpty()){ root = stack.pop(); System.out.println(root.getVal()); root = root.getRight(); } } }
後序(遞迴)
public void postOrder(TreeNode root){
if(root != null){
postOrder(root.getLeft());
postOrder(root.getRight());
System.out.println(root.getVal());
}
}
後序(非遞迴)
public static void preOrder(TreeNode root){ Stack<TreeNode> stack = new Stack<TreeNode>(); Stack<TreeNode> output = new Stack<TreeNode>(); TreeNode node = root; while(!stack.isEmpty() || node != null){ if(node != null){ output.push(node); stack.push(node); node = node.getRight(); } else { node = stack.pop(); node = node.getLeft(); } } while(output.size() > 0){ list.add(output.pop().getVal()); } }
層次遍歷
public void levelOrder(TreeNode root){
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
while(!queue.isEmpty()){
TreeNode node = queue.pop();
System.out.println(root.getVal());
if(node.getLeft() != null){
queue.add(node.getLeft());
}
if(node.getRight() != null){
queue.add(node.getRight());
}
}
}