二叉樹的層序遍歷


102 二叉樹的層序遍歷

這個題目和書上不一樣的地方就是不同的層的放在一個vector中,每層可以區分開。於是,我們可以定義一個count,用來計算每一層的結點數。

用隊列來存放樹的結點。

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<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> v1;
        
        if(root==NULL){//首先判斷根節點是否為空
            return v1;
        }
        
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty()){
            int count = q.size();//當下面的循環結束一次,此時queue中的所有結點剛好是下一層的是所有結點,計算數量。
            vector<int> v;
            while(count > 0){//這個循環完,就相當於一層結束。
                TreeNode* cur = q.front();
                v.push_back(cur->val);//要是沒有前面判斷root根節點是否為空的操作,當根節點為空時,這一步就會出現空指針現象。
                
                q.pop();
                
                if(cur->left != NULL){
                    q.push(cur->left);
                }
                if(cur->right != NULL){
                    q.push(cur->right);
                }
                count--;
            }
            v1.push_back(v);
        }
        return v1;
    }
};

 

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<List<Integer>> levelOrder(TreeNode root) {
        if(root == null){
            return new ArrayList<>();
        }
        List<List<Integer>> res = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while(!queue.isEmpty()){
            int count = queue.size();
            List<Integer> list = new ArrayList<Integer>();
            while(count>0){
                TreeNode node = queue.poll();
                list.add(node.val);
                if(node.left != null){
                    queue.add(node.left);
                }
                if(node.right != null){
                    queue.add(node.right);
                }
                count--;
            }
            res.add(list);
        }
        return res;
    }
}

Java中對於Queue來說,就是一個FIFO(先進先出)的隊列,添加元素只能在隊尾,移除只能在隊首。

對於這一組方法,成功返回true,在操作失敗時拋出異常,這是與下面一組方法的主要區別。

add(E e):添加一個元素到隊尾

remove():獲取隊首的元素,並從隊列中移除

element():獲取隊首的元素,但不從隊列中移除

 

這一組,成功返回true,失敗時返回一個特殊值(取決於操作,為NULL或false),offer(E e)操作是專為容量受限的隊列實現而設計的;在大多數實現中,插入操作不會失敗。

offer(E e):添加一個元素到隊尾

poll():獲取隊首的元素,並從隊列中移除

peek():獲取隊首的元素,但不從隊列中移除


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM