二叉树的最小深度
题目:
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.
思路:
树的操作首先想到的方法是用递归,大致思路是:
若为空树返回为0;若左子树为空,则返回右子树的最小深度+1(要加上根这一层);若右子树为空,则返回左子树的最小深度+1;若左右子树都不为空,则取左、右最小深度的较小值+1
递归实现较为简单,下面说下非递归的实现,大致思路是:
对树进行层序遍历,找到第一个左右都为NULL情况,返回当前树的高度。
非递归的实现:
/** * 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) { queue<TreeNode* > q; if (root){ q.push(root); } int level = 0; while (!q.empty()){ ++level; TreeNode * node = q.front(); for (int i=0; i<q.size(); ++i){ q.pop(); if (NULL == node->left && NULL == node->right){ return level; } } if (node->left){ q.push(node->left); } if (node->right){ q.push(node->right); } } return level; } };