首页 > 代码库 > Binary Tree Preorder Traversal

Binary Tree Preorder Traversal

地址: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