中序遍历二叉树
给定一个二叉树,返回它的中序 遍历。
示例:

解答思路:可以套用模板
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer>res=new ArrayList<>();
if(root==null)
return res;
Stack<TreeNode>stack=new Stack<>();
TreeNode cur=root;
while(!stack.isEmpty()||cur!=null){
while(cur!=null){
stack.push(cur);
cur=cur.left;
}
cur=stack.pop();
res.add(cur.val);
cur=cur.right;
}
return res;
}
}
非递归遍历二叉树的方式有很多,最常用的就是用栈的思想来模拟递归了,当然用栈写出来的也是五花八门,我这里取了一种可以统一前序和中序和后序的栈的非递归写法,这样是为了更方便的理解和记忆。
非递归前序二叉树遍历模板
class Solution{
public List<Integer>preorder(TreeNode root){
ArrayList<Integer>res=new ArrayList<>();
if(root==null)
return res;
Stack<TreeNode>stack=new Stack<>();
TreeNode cur=root;
while(!stack.isEmpty()||cur!-null){
while(cur!=null){
res.add(cur.val);
stack.push(cur);
cur=cur.left;
}
cur=stack.pop();
cur=cur.right;
}
}
}

没啥难度,就是利用flag变向+常规层次遍历+双向队列
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>>res=new ArrayList<>();
if(root==null)
return res;
LinkedList<TreeNode>list=new LinkedList<>();
list.offer(root);
boolean flag=true;
while(!list.isEmpty()){
List<Integer>ll=new ArrayList<>();
int len=list.size();
if(flag) {
for (int i = 0; i < len; i++) {
TreeNode cur = list.pollFirst();
ll.add(cur.val);
if (cur.left != null)
list.offer(cur.left);
if (cur.right != null)
list.offer(cur.right);
}
flag=false;
}else{
for(int i=0;i<len;i++){
TreeNode cur=list.pollLast();
ll.add(cur.val);
if(cur.right!=null)
list.addFirst(cur.right);
if(cur.left!=null)
list.addFirst(cur.left);
}
flag=true;
}
res.add(ll);
}
return res;
}
}

class Solution {
int pos;
int distance(int[]a,int b){
for(int i=0;i<a.length;i++){
if(a[i]==b)
return i;
}
return -1;
}
TreeNode Helper(int l, int r, int []pre,int []in){
if(l>=r)
return null;
TreeNode root=new TreeNode(pre[pos++]);
int m=distance(in,root.val);
root.left=Helper(l,m,pre,in);
root.right=Helper(m+1,r,pre,in);
return root;
}
public TreeNode buildTree(int[]preorder,int[]inorder){
return Helper(0,preorder.length,preorder,inorder);
}
}

public class Solution {
public void connect(TreeLinkNode root) {
if(root==null)
return;
if(root.left!=null){
root.left.next=root.right;
if(root.next!=null){
root.right.next=root.next.left;
}
}
connect(root.left);
connect(root.right);
}
}

套用中序遍历模板即可
public int kthSmallest(TreeNode root){
Stack<TreeNode>stack=new Stack<>();
TreeNode cur=root;
while(!stack.isEmpty()||cur!=null){
while(cur!=null){
stack.push(cur);
cur=cur.left;
}
cur=stack.pop();
k--;
if(k==0)
return cur.val;
cur=cur.right;
}
return -1;
}
1242

被折叠的 条评论
为什么被折叠?



