[Daily question] 30: Preorder traversal of binary tree

Title description

Given a binary tree, return its preorder traversal.

Example:

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

输出: [1,2,3]

Advanced: The recursive algorithm is very simple, can you complete iterative algorithm?

Recursive algorithm

Code answer

/**
 * 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 {
    vector<int> v;
public:
    vector<int> preorderTraversal(TreeNode* root) {

        if(root){
            v.push_back(root->val);
            preorderTraversal(root->left);
            preorderTraversal(root->right);
        }

        return v;
    }
};

Non-recursive algorithm

Code answer

class Solution {
    stack<TreeNode*> stk;
public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> vec;
        TreeNode* temp = root;
        while(temp){
            vec.push_back(temp -> val);
            if(temp->right){
                stk.push(temp->right);
            }
            if(temp->left){
                temp = temp->left;
            }
            else{
            	// 防止根节点为空
                if(stk.empty()){
                    break;
                }
                temp = stk.top();
                stk.pop();
            }
        }
        return vec;
    }
};
Published 152 original articles · praised 45 · 10,000+ views

Guess you like

Origin blog.csdn.net/AngelDg/article/details/105392763