Leetcode dfs Binary Tree Postorder Traversal

來源:互聯網
上載者:User

標籤:des   style   http   color   os   io   ar   for   div   

Binary Tree Postorder Traversal Total Accepted: 28560 Total Submissions: 92333My Submissions

Given a binary tree, return the postorder traversal of its nodes‘ values.

For example:
Given binary tree {1,#,2,3},

   1         2    /   3

return [3,2,1].

Note: Recursive solution is trivial, could you do it iterativel



題意:後序遍曆,不過給出了函式宣告,限制了實現方式
思路:採用遞迴實現。因為函式宣告是返回一個vector<int>,所以每個子樹返回的是該子樹的後序遍曆的結果
按照 左、右、根的次序把根和左右子樹的vector合并起來就可以了
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:


    vector<int> postorderTraversal(TreeNode *root) {
    vector<int> post;
    if(root == NULL) return post;
    TreeNode *left = root->left;
    TreeNode *right = root->right;
    
    if(left) {
    vector<int> left_vector = postorderTraversal(left);
    post.insert(post.end(), left_vector.begin(), left_vector.end());
    }
    if(right){
    vector<int> right_vector = postorderTraversal(right);
    post.insert(post.end(), right_vector.begin(), right_vector.end());
    }
    post.push_back(root->val);
    
    return post;
    }
};

Leetcode dfs Binary Tree Postorder Traversal

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.