題目:
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; } };