首页 > 其他 > 详细

p31 二叉树的逆层序遍历

时间:2020-03-14 15:34:54      阅读:69      评论:0      收藏:0      [点我收藏+]

一:解题思路

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

二:完整代码示例 (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;
    }
}

 

p31 二叉树的逆层序遍历

原文:https://www.cnblogs.com/repinkply/p/12492132.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!