中序遍历,使用递归很简单,这里使用迭代的思想,先用一个栈将节点的左节点都压入栈中,在取出一个节点来,将它视为根节点,(因为他的左子树要么为空,要么就是栈中弹出来了已经遍历了),保存他的值,再处理他的右子树,以此类推
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
if(root==null) return new ArrayList<Integer>();
Stack<TreeNode> stack=new Stack<>();
List<Integer> res=new ArrayList<>();
while(root!=null||!stack.isEmpty()){
while(root!=null){
stack.push(root);
root=root.left;
}
if(!stack.isEmpty()){
TreeNode node=stack.pop();
res.add(node.val);
root=node.right;
}
}
return res;
}
}
没有想到好办法,就是层次遍历然后用一个标记他的方向,交替进行
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
if(root==null) return new ArrayList<>();
boolean dir=false;//标志方向
Queue<TreeNode> queue=new LinkedList<>();
List<List<Integer>> res=new ArrayList<>();
queue.add(root);
while(!queue.isEmpty()){
List<Integer> list=new ArrayList<>();
int size=queue.size();//遍历每一层数据
for(int i=0;i<size;i++){
TreeNode node=queue.poll();
list.add(node.val);
if(node.left!=null)
queue.offer(node.left);
if(node.right!=null)
queue.offer(node.right);
}
if(dir){Collections.reverse(list);dir=false;}//方向为true就反转当前list
else dir=true;//方向交替
res.add(list);
}
return res;
}
}
这个题目需要好好注意,使用前序和中序构造出树,记住一个思想,先将前序的第一个数取出来,就是根节点,再在中序遍历中找到这个节点,左边的都是他的左子树,右边为右子树,不断这样拆分,直到不能拆分为止
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
List<Integer> preroot=new ArrayList<>();//前序遍历
List<Integer> inroot=new ArrayList<>();//中序遍历
for(int i=0;i<preorder.length;i++){
preroot.add(preorder[i]);
inroot.add(inorder[i]);
}
return backtracking(preroot,inroot);
}
public TreeNode backtracking(List<Integer> preroot,List<Integer> inroot){
if(inroot.size()==0) return null;
int pre=preroot.remove(0);
TreeNode root=new TreeNode(pre);
int mid=inroot.indexOf(pre);
root.left=backtracking(preroot,inroot.subList(0,mid));
root.right=backtracking(preroot,inroot.subList(mid+1,inroot.size()));
return root;
}
}
这个很好理解,但是使用指针有点难理解,这里配上链接,有时间去慢慢消化