【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.

题目要求:
   求二叉树的最短从根节点到叶子节点的深度,这道题与典型的求二叉树的深度很相似,只是二叉树的深度求的是最长,这道题求的是最短。

  
      对于上面这颗二叉树,依次访问从上向下递归访问,对节点1来说,它左节点为2,右节点为3,对1节点最短深度来说,就是做已2为节点的左子树和以3为节点的右子树最小深度+1
     当递归到节点2时,其右子树为空,所以它的最小深度只可能来自左子树,这样不断递归访问子树,当访问到的节点为空时,结束递归。
     根据上面的分析不难写出下面的代码

   
<pre name="code" class="cpp"> int run(TreeNode *root) {
        if (root == NULL)
		return 0;
        if(root->left==NULL & root->right!=NULL){
            return run(root->right) + 1;
        }
       if(root->left!=NULL & root->right==NULL){
            return run(root->left) + 1;
        }
		return min(run(root->left) + 1, run(root->right) + 1);
    }




  测试
       输入上图的二叉树

  
#include<iostream>
using namespace std;

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

int min(int a, int b){
	return a < b ? a : b;
}
int minDepth(TreeNode *root) {
	if (root == NULL)
		return 0;
	if (root->left == NULL & root->right != NULL){
		return minDepth(root->right) + 1;
	}
	if (root->left != NULL & root->right == NULL){
		return minDepth(root->left) + 1;
	}
	return min(minDepth(root->left) + 1, minDepth(root->right) + 1);
}
int main(){
	TreeNode *node1 =new TreeNode(1);
	TreeNode *node2 = new TreeNode(2);
	TreeNode *node3 = new TreeNode(3);
	TreeNode *node4 = new TreeNode(4);
	TreeNode *node5 = new TreeNode(5);
	TreeNode *node6 = new TreeNode(6);
	node1->left = node2;
	node1->right = node3;
	node2->left = node4;
	node3->left = node5;
	node5->right = node6;
	cout << minDepth(node1) << endl;
	cin.get();
	return 0;
}

输出
  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章