leetcode - Minimum Depth of Binary Tree
leetcode - 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: void dfs(TreeNode* root, int &MIN, int deep){ if(root == NULL) return; if(root->right == NULL && root->left == NULL){ if(MIN>deep) MIN = deep; //遇到叶子节点后,判断是否为最新的最小值。 } dfs(root->right, MIN, deep+1); dfs(root->left, MIN, deep+1); } int minDepth(TreeNode* root) { if(root == NULL) return 0; int MIN = INT_MAX;//初始为很大的数 dfs(root, MIN, 1); return MIN; } };
原本以为将求最大树深度的代码中max该为min即可,结发现并不是这样。
求最大深度时,对于NULL节点可以均看做深度为0,当一个子节点存在,另一个为NULL时,显然由于NULL的节点深度为0,求max的时候肯定不会取到,对于这个“不存在的子节点”不会影响结果;
而求最小深度时,如果对NULL节点看做深度为0,对于根节点显然正确。但是,当遇到一个子节点存在,另一个为NULL的情况时,会在求min的时候将这个“不存在的节点”看做最短的深度,然而事实上NULL不算做一个叶子,是不应该算进去的。
所以需要判断何时是叶子节点:当左右子节点均为NULL,说明为叶子节点。
http://www.cnblogs.com/zsboy/p/3887325.html
http://blog.csdn.net/sbitswc/article/details/26526031