Binary Tree Traversal

Preorder:

Given a binary tree, return the preorder traversal of its nodes' values.

Example:

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [1,2,3]

Approach #1: Recurisive.

/**
 * 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> ans;
        helper(root, ans);
        return ans;
    }
    
private:
    void helper(TreeNode* root, vector<int>& ans) {
        if (root == NULL) return ;
        ans.push_back(root->val);
        helper(root->left, ans);
        helper(root->right, ans);  
    }
};

Approach #2: Iteratively.[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> res = new LinkedList<Integer>();
        Stack<TreeNode> todo = new Stack<TreeNode>();
        TreeNode cur = root;
        while (cur != null) {
            res.add(cur.val);
            if (cur.right != null) {
                todo.push(cur.right);
            }
            cur = cur.left;
            if (cur == null && !todo.isEmpty()) {
                cur = todo.pop();
            }
        }
        return res;
    }
}

Approach #3: Morris Traversal.[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) {
        TreeNode* cur = root;
        vector<int> nodes;
        while (cur) {
            if (cur->left) {
                TreeNode* pre = cur->left;
                while (pre->right && (pre->right != cur)) {
                    pre = pre->right;
                }
                if (!(pre->right)) {
                    nodes.push_back(cur->val);
                    pre->right = cur;
                    cur = cur->left;
                } else {
                    pre->right = NULL;
                    cur = cur->right;
                }
            } else {
                nodes.push_back(cur->val);
                cur = cur->right;
            }
        }
        return nodes;
    }
};

Using Morris Traversal can don't use recurisive and stack and space complex is O(1).

猜你喜欢

转载自www.cnblogs.com/ruruozhenhao/p/9978743.html