其他分享
首页 > 其他分享> > p31 二叉树的逆层序遍历

p31 二叉树的逆层序遍历

作者:互联网

一:解题思路

这道题目是二叉树层序遍历的变体,只需要在二叉树层序遍历的结果上,将结果沿中轴线对调一下就行。

二:完整代码示例 (C++版和Java版)

C++:

//Time:O(n),Space:O(n)
class Solution 
{
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root)
    {
        vector<vector<int>> result;
        queue<TreeNode*> q;

        if (root != NULL)
            q.push(root);

        while (!q.empty())
        {
            int size = q.size();
            vector<int> elem;

            for (int i = 0; i < size; i++)
            {
                TreeNode* node = q.front();
                q.pop();

                elem.push_back(node->val);

                if (node->left != NULL) q.push(node->left);
                if (node->right != NULL) q.push(node->right);
            }

            result.push_back(elem);
        }

        for (int i = 0; i < result.size() / 2; i++)
        {
            int j = result.size() - 1 - i;
            vector<int> temp = result[i];
            result[i] = result[j];
            result[j] = temp;
        }

        return result;
    }
};

Java:

class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root)
    {
        List<List<Integer>> result=new ArrayList<>();
        Queue<TreeNode> q=new LinkedList<>();

        if(root!=null)
            q.add(root);

        while(!q.isEmpty())
        {
            int size=q.size();
            List<Integer> elem=new ArrayList<>();

            for(int i=0;i<size;i++)
            {
                TreeNode node=q.poll();
                elem.add(node.val);

                if(node.left!=null) q.add(node.left);
                if(node.right!=null) q.add(node.right);
            }

            result.add(elem);
        }

        for(int i=0;i<result.size()/2;i++)
        {
             int j=result.size()-1-i;
             
             List<Integer> temp=result.get(j);
             result.set(j,result.get(i));
             result.set(i,temp);
        }

        return result;
    }
}

 

标签:result,node,int,root,二叉树,push,p31,逆层序,size
来源: https://www.cnblogs.com/repinkply/p/12492132.html