涉及的几个类
Stack (栈)是Vector 的一个子类
Queue(队列)
Stack <TreeNode> st=new Stack<>();
//基本操作
st.pop() //弹栈,返回弹出的元素
st.push() //压栈
st.peek() //返回栈顶元素
//用栈维护
//队列
Queue<TreeNode> qu=new LinkedList<>();
qu.add()(不可以增加null)或者qu.offer()(可以增加null) //增加一个元素
qu.remove()(失败throws NoSuchElementException)或者qu.poll()(失败返回null)//返回
qu.element()(失败throws)或者 qu.peek() (失败返回null);
二叉树的遍历问题:
非递归的四种遍历方式:
1.前序遍历
先入栈 root
然后执行 弹出栈顶并且输出然后压栈 右节点和左节点。(先右后左)
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
Stack<TreeNode> st=new Stack<>();
List<Integer> result=new ArrayList<>();
if (root==null) return result;
st.push(root);
TreeNode temp;
while(!st.empty())
{
temp=st.pop();
result.add(temp.val);
if (temp.right!=null) st.push(temp.right);
if (temp.left!=null) st.push(temp.left);
}
return result;
}
}
2.后序遍历:
就是先序遍历中压栈(先左后右) 之后将得到的值反转。
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
Stack<TreeNode> st=new Stack<>();
List<Integer> result=new ArrayList<>();
if (root==null) return result;
st.push(root);
TreeNode temp;
while(!st.empty())
{
temp=st.pop();
result.add(temp.val);
if (temp.left!=null) st.push(temp.left);
if (temp.right!=null) st.push(temp.right);
}
Collections.reverse(result);
return result;
}
}
3.中序遍历
中序遍历有些麻烦,维护一个栈 和一个指针p 。
每次将p不断向左边递进直至p==null 之后弹栈 另p=st.pop().right;
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result=new ArrayList<Integer>();
if (root==null) return result;
TreeNode p=root;
Stack<TreeNode> st=new Stack<TreeNode>();
while (p!=null || (!st.empty()))
{
while (p!=null)
{
st.push(p);
p=p.left;
}
if (!st.empty())
{
TreeNode temp=st.pop();
result.add(temp.val);
p=temp.right;
}
}
return result;
}
}
4.层序遍历
只需要维护一个队列即可 相对简单 Queue