剑指offer(11)-从上往下打印二叉树

来源:互联网 发布:蜗牛卡充值话费软件 编辑:程序博客网 时间:2024/06/05 20:21

题目:从上往下打印出二叉树的每个结点,同一层的结点按从左到右的顺序打印。二叉树结点的定义如下:

struct TreeNode {    int val;    struct TreeNode *left;    struct TreeNode *right;    TreeNode(int x) :            val(x), left(NULL), right(NULL) {    }};

简单的层序遍历,也可以理解成简单的BFS,要记得使用队列来保存访问过结点的子结点,按序保存,按序打印。

class Solution {public:    vector<int> PrintFromTopToBottom(TreeNode *root) {        queue<TreeNode*> deq;        vector<int> rval;        if (root == NULL)            return rval;        deq.push(root);        while (deq.size())            {            TreeNode* ptr = deq.front();            rval.push_back(ptr->val);            deq.pop();            if (ptr->left != NULL) deq.push(ptr->left);            if (ptr->right != NULL) deq.push(ptr->right);         }        return rval;    }};

LeetCode上的题目变形1:
Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).

For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]

要求我们每一次将当前层的结点保存起来,然后再按层存入二维向量中,这时候我们需要判断队列的长度,按每层入队的顺序依次保存元素:

/** * 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>> result;        if (root == NULL)            return result;        queue<TreeNode*> que;        que.push(root);        while (!que.empty())        {            vector<int> res;            int qsize = que.size();            for (int i = 0; i < qsize; i++) {                TreeNode* ptr = que.front();                que.pop();                res.push_back(ptr->val);                if (ptr->left != NULL) que.push(ptr->left);                if (ptr->right != NULL) que.push(ptr->right);            }            result.push_back(res);        }        return result;    }};

LeetCode上的题目变形2:
111. Minimum Depth of Binary Tree
Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

/** * 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:    int minDepth(TreeNode* root) {        if (root == NULL)          return 0;        int LeftH = minDepth(root->left);        int RightH = minDepth(root->right);        if (LeftH == 0)          return RightH + 1;        else if (RightH == 0)          return LeftH + 1;        else          return min(LeftH,RightH) + 1;    }};
1 0
原创粉丝点击