二叉树的先序遍历
public int[] preorderTraversal (TreeNode root) {
List<Integer> list = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
while (!stack.empty() || root!=null){
while (root!=null){
list.add(root.val);
stack.push(root);
root = root.left;
}
root = stack.pop();
root = root.right;
}
int[] ans = new int[list.size()];
for(int i=0;i<ans.length;i++){
ans[i] = list.get(i);
}
return ans;
}
二叉树的中序遍历非递归
public int[] inorderTraversal (TreeNode root) {
List<Integer> list = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
while (!stack.empty() || root!=null){
while (root!=null){
stack.push(root);
root = root.left;
}
root = stack.pop();
list.add(root.val);
root = root.right;
}
int[] ans = new int[list.size()];
for(int i=0;i<ans.length;i++){
ans[i] = list.get(i);
}
return ans;
}
二叉树的后序遍历非递归版本 因为二叉树的先序遍历是:根左右 我们可以通过改变先序顺序得到:根右左 然后对根右左 进行反向遍历就可以得到 左右根
public int[] postorderTraversal (TreeNode root) {
List<Integer> list = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
while (!stack.empty() || root!=null){
while (root!=null){
list.add(root.val);
stack.push(root);
root = root.right;
}
root = stack.pop();
root = root.left;
}
int[] ans = new int[list.size()];
for(int i=ans.length-1;i>=0;i--){
ans[i-ans.length+1] = list.get(i);
}
return ans;
}
|