中序遍历
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;
}
}
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
while (root!=null || !stack.isEmpty())
{
while (root!=null)
{
stack.push(root);
root=root.left;
}
root=stack.pop();
ans.add(root.val);
root=root.right;
}
return ans;
}
}
前序遍历
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;
}
}
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
while (root!=null || !stack.isEmpty())
{
while (root!=null)
{
ans.add(root.val);
stack.push(root);
root=root.left;
}
root=stack.pop();
root=root.right;
}
return ans;
}
}
后序遍历
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;
}
}
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode prev=null;
if (root==null)
return ans;
while (root!=null || !stack.isEmpty())
{
while (root!=null)
{
stack.push(root);
root=root.left;
}
root=stack.pop();
if (root.right==null || root.right==prev)
{
ans.add(root.val);
prev=root;
root=null;
}
else {
stack.push(root);
root=root.right;
}
}
return ans;
}
}