Binary Tree Level Order Traversal II <leetcode>

來源:互聯網
上載者:User

標籤:des   style   blog   color   io   ar   for   div   代碼   

Given a binary tree, return the bottom-up level order traversal of its nodes‘ values. (ie, from left to right, level by level from leaf to root).

For example:
Given binary tree {3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[
[15,7],
[9,20],
[3]
]

思路:本來想到用分支限界,但是代碼寫的很複雜,沒有控制住,後來在網上看到一個方法,很簡單,直接遍曆,有些代碼挺巧妙的,代碼如下:

 

 1 /** 2  * Definition for binary tree 3  * struct TreeNode { 4  *     int val; 5  *     TreeNode *left; 6  *     TreeNode *right; 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8  * }; 9  */10  struct node11  {12      TreeNode *val;13      int dep;14  };15 class Solution {16 public:17     vector<vector<int>>  result;18     vector<int>  temp;19     vector<vector<int> > levelOrderBottom(TreeNode *root) {20         doit(root,0);21         reverse(result.begin(),result.end());22         return result;23     }24     25     void doit(TreeNode *root,int level)26     {27         if(root==NULL)  return;28         else29         {30             if(level==result.size())31             {32                  vector<int> v;33                  result.push_back(v);34             }35             result[level].push_back(root->val);36             doit(root->left,level+1);37             doit(root->right,level+1);38         }39     }40 };

 

Binary Tree Level Order Traversal II <leetcode>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.