【LeetCode】144. 二叉樹的前序遍歷-遞歸和非遞歸

LeetCode鏈接:https://leetcode-cn.com/problems/binary-tree-preorder-traversal/

給定一個二叉樹,返回它的 前序 遍歷。

 示例:

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

輸出: [1,2,3]


一,非遞歸解決方案:

     根據前序遍歷訪問的順序,優先訪問根結點,然後再分別訪問左孩子和右孩子。即對於任一結點,其可看做是根結點,因此可以直接訪問,訪問完之後,若其左孩子不爲空,按相同規則訪問它的左子樹;當訪問其左子樹時,再訪問它的右子樹。因此其處理過程如下:

  對於任一結點cur:

     1)訪問結點cur,並將結點cur入棧;

     2)判斷結點cur的左孩子是否爲空,若爲空,則取棧頂結點並進行出棧操作,並將棧頂結點的右孩子置爲當前的結點cur,循環至1);若不爲空,則將cur的左孩子置爲當前的結點cur;

     3)直到cur爲NULL並且棧爲空,則遍歷結束。

/**
 * 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:
    /*void preorder(TreeNode* root,vector<int>& v)
    {
        if(root == 0)
            return;
        v.push_back(root->val);
        preorder(root->left,v);
        preorder(root->right,v);
    }*/
    vector<int> preorderTraversal(TreeNode* root) 
    {
        vector<int> v;
        //preorder(root,v);
        TreeNode* cur = root;
        stack<TreeNode*> st;
        while(cur || !st.empty())
        {
            while(cur)
            {
                st.push(cur);
                v.push_back(cur->val);
                cur = cur->left;
            }
            TreeNode* top = st.top();
            st.pop();
            cur = top->right;
        }
        return v;
    }
};

  

二,進階: 遞歸算法很簡單,你可以通過迭代算法完成嗎?

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int *p;
int size;
void _pre(struct TreeNode *root){
    if(root == NULL){
        return;
    }
    p[size] = root->val;
    size++;
    _pre(root->left);
    _pre(root->right);
}
int* preorderTraversal(struct TreeNode* root, int* returnSize) {
    p = (int *)malloc(sizeof(int)*100000);
    size = 0;
    _pre(root);
    *returnSize = size;
    return p;
}

三,Python方案:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def preorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if root == None:
            return[]
        return
[root.val]+self.preorderTraversal(root.left)+self.preorderTraversal(root.right)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章