二叉树的三种遍历我们都知道有 前序遍历、中序遍历和后序遍历。
对于这三种遍历的递归写法,我们会觉得十分好理解,但是发现对于其非递归写法还是认为很复杂。所以就记录于此,希望有一天都能凭借自己本事写出来。加油~
List<Integer> res = new ArrayList<Integer>();
/**
* 前序遍历 非递归 写法
* @param node
*/
public List<Integer> beforeOrder(Node root) {
if(root == null)
return res;
Stack<Node> stack = new Stack<Node>();
//将根节点入栈
stack.push(root);
//若栈非空,则继续循环
while(!stack.isEmpty()) {
Node node = stack.pop(); //根结点出栈
res.add(node.data);
//因为栈遵循“先进后出”原则,所以先将右孩子入栈
if(node.rightChild != null)
stack.push(node.rightChild);
if(node.leftChild != null)
stack.push(node.leftChild);
}
return res;
}
/**
* 中序遍历 左、中、右
* @param root
* @return
*/
public List<Integer> inOrder(Node root){
if(root==null)
return res;
Stack<Node> stack = new Stack<Node>();
Node node = root;
//若栈非空或者当前结点非空
while(!stack.isEmpty() || node!=null) {
if(node!=null) { //如果当前结点非空
stack.push(node); //入栈
node = node.leftChild; //指向左孩子
} else { //如果当前结点空,但栈非空
node = stack.pop(); //出栈
res.add(node.data);
node = node.rightChild; //指向右孩子
}
}
return res;
}
/**
* 后序遍历 左、右、中
* @param root
* @return
*/
public List<Integer> afterOrder(Node root){
if(root==null)
return res;
Stack<Node> stack = new Stack<Node>();
stack.push(root); //因为根节点最后遍历,所以先将根节点入栈
//若栈非空
while(!stack.isEmpty()) {
Node node = stack.pop();//首先出栈的是根节点,其后先出右结点、再出左结点
if(node.leftChild!=null)
stack.push(node.leftChild); //将左孩子入栈
if(node.rightChild!=null)
stack.push(node.rightChild);//将右孩子入栈
//把node的值插到res首部。因为while循环中遍历顺序是中右左,插到首部后顺序就是左右中
res.add(0, node.data);
}
return res;
}