144 二叉树的前序遍历
这个思路与二叉树的中序遍历一样,只是先把每一个新的根结点,先把起值放入要返回的列表,然后把它存起来,等遍历完左子树然后返回继续访问其右子树。
C++代码
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> preorderTraversal(TreeNode* root) { vector<int> a; stack<TreeNode*> s; TreeNode* cur = root; while(!s.empty() || cur!=NULL){ if(cur!=NULL){ a.push_back(cur->val); s.push(cur); cur = cur->left; }else{ cur = s.top(); s.pop(); cur = cur->right; } } return a; } };
Java代码
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<Integer> preorderTraversal(TreeNode root) { List<Integer> list = new ArrayList<>(); Stack<TreeNode> s = new Stack<>(); TreeNode cur = root; while(cur!=null || !s.isEmpty()){ if(cur!=null){ list.add(cur.val); s.push(cur); cur = cur.left; }else{ cur = s.pop(); cur = cur.right; } } return list; } }