前序遍历(root,left,right)
用栈实现
只要当前节点不为空或者栈中还有元素就执行以下步骤
1先把根节点作为当前节点
2把当前节点的右节点压栈,把当前节点的左节点当做当前节点
3读取当前节点的值,如果当前节点的左节点不为null,重复步骤2,否则, 执行步骤4
4则把栈顶节点弹出,作为当前节点,回到步骤2
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result=new ArrayList<Integer>();
Stack stack=new Stack();
TreeNode currentNode=root;
while(currentNode!=null||!stack.empty()){
if(currentNode==null){
currentNode=(TreeNode) stack.pop();
}
result.add(currentNode.val);
if(currentNode.right!=null){
stack.push(currentNode.right);
}
currentNode=currentNode.left;
}
return result;
}
}
中序遍历(left, root ,right)
将左边节点依次压栈,当左边没有节点后读取当前节点,把右节点作为当前节点
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result=new ArrayList<Integer>();
if(root==null)
return result;
Stack<TreeNode> s=new Stack<TreeNode>();
while(root!=null||!s.isEmpty()){
while(root!=null){
s.push(root);
root=root.getLeft();
}
root=s.pop();
result.add(root.getVal());
root=root.getRight();
}
return result;
}
}
后续遍历
visit中存储访问过的节点
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> result=new ArrayList<Integer>();
Stack<TreeNode> stack=new Stack<TreeNode>();
Map<TreeNode,Boolean> visit=new HashMap<TreeNode,Boolean>();
if(root==null)
return result;
stack.push(root);
TreeNode currentNode;
while(!stack.empty()){
currentNode=stack.peek();
if(currentNode.left!=null&&!visit.containsKey(currentNode.left)){
stack.push(currentNode.left);
visit.put(currentNode.left, true);
}else if(currentNode.right!=null&&!visit.containsKey(currentNode.right)){
stack.push(currentNode.right);
visit.put(currentNode.right, true);
}else{
result.add(currentNode.val);
stack.pop();
}
}
return result;
}
}
后续遍历更简单的实现
后续遍历访问顺序是左右根,可以用根右左访问到的节点顺序反过来即可
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> result=new ArrayList<Integer>();
Stack<TreeNode> stack=new Stack<TreeNode>();
TreeNode currentNode=root;
while(currentNode!=null||!stack.empty()){
if(currentNode==null){
currentNode= stack.pop();
}
result.add(currentNode.val);
if(currentNode.left!=null){
stack.push(currentNode.left);
}
currentNode=currentNode.right;
}
Collections.reverse(result);
return result;
}
}