·  阅读 55

# 二叉树节点定义

``````class TreeNode {
int val;
TreeNode left;
TreeNode right;

//    TreeNode() {}
TreeNode(int val) {
this.val = val;
}

TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}

# 栈迭代-修改栈迭代方式的前序遍历

``````public List<Integer> preorder(TreeNode root){
Stack<TreeNode>stack = new Stack<>();

while(root!=null || !stack.isEmpty()){
while(root!=null){
stack.push(root);
root = root.left;
}
root = stack.pop();
root = root.right;
}
return list;
}

``````public List<Integer> preorder(TreeNode root){
Stack<TreeNode>stack = new Stack<>();

while(root!=null || !stack.isEmpty()){
while(root!=null){
stack.push(root);
root = root.right;
}
root = stack.pop();
root = root.left;
}
return list;
}

# 栈迭代后序遍历

``````public List<Integer> preorder(TreeNode root){
List<Integer> list = new ArrayList<>();
Stack<TreeNode>stack = new Stack<>();
TreeNode pre;
while(root!=null || !stack.isEmpty()){
while(root!=null){
stack.push(root);
root = root.left;
}
root = stack.pop();
if(root.right==null || root.right==pre){
pre = root;
root = null;
}else{
stack.push(root);
root = root.right;
}
}
return list;
}

# morris 后序遍历

``````public List<Integer> preorder(TreeNode root){
List<Integer> list = new ArrayList<>();
root = new TreeNode(-1,root,null);

TreeNode predecessor;
while(root!=null){
if(root.left!=null){
predecessor = root.left;
while(predecessor.right!=null&&predecessor.right!=root){
predecessor = predecessor.right;
}
if(predecessor.right==null){
predecessor.right = root;
root = root.left;
}else{
predecessor = null;
root = root.right;
}

}else{
root = root.right;
}
}
return list;
}

private void addnode(TreeNode root, List<Integer> list) {
//遍历链表
TreeNode cur = reverseList(root);
while (cur != null) {
cur = cur.right;
}

reverseList(root);

}

//反转链表
TreeNode pre = null;
while (cur != null) {
TreeNode next = cur.right;
cur.right = pre;
pre = cur;
cur = next;
}
return pre;
}