标签:二叉树前序遍历非递归实现
地址:https://oj.leetcode.com/problems/binary-tree-preorder-traversal/
题意实现二叉树的前序遍历。利用栈实现。
public class Solution {
       public List<Integer> preorderTraversal(TreeNode root) {
    	List<Integer > ans = new ArrayList<>();
    	TreeNode p = root;
    	Stack<TreeNode> st = new Stack<TreeNode>();
    	while(p!=null || st.size()!=0){
    		while(p!=null){
    			ans.add(p.val);
    			st.push(p);
    			p= p.left;
    		}
    		if(st.size()!=0){
    			p = st.peek();
    			st.pop();
    			p = p.right;
    		}
    	}
    	return ans;
    }
}
 
Binary Tree Preorder Traversal
标签:二叉树前序遍历非递归实现
原文地址:http://blog.csdn.net/huruzun/article/details/38986461