Skip to content

Latest commit

 

History

History
53 lines (48 loc) · 1.18 KB

144BinaryTreePreorderTraversal.md

File metadata and controls

53 lines (48 loc) · 1.18 KB

144. Binary Tree Preorder Traversal

给定一个二叉树,返回它的 前序 遍历。

 示例:

输入: [1,null,2,3]  
   1
    \
     2
    /
   3 

输出: [1,2,3]

进阶: 递归算法很简单,你可以通过迭代算法完成吗?

解法:利用栈辅助

/**
 * 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) {
        stack<TreeNode*> rights;
        vector<int> results;
        TreeNode* current = root;
        while(current != NULL) {
            results.push_back(current->val);
            if(current->left!=NULL) {
                if(current->right!=NULL) rights.push(current->right);
                current = current->left;
            } else if(current->right!=NULL) {
                current = current->right;
            } else if(rights.size()>0) {
                current = rights.top();
                rights.pop();
            } else {
                current = NULL;
            }
        }
        return results;
    }
};