minimum-depth-of-binary-tree--《LeetCode》

来源:互联网 发布:淘宝二级页面设计 编辑:程序博客网 时间:2024/06/07 19:12

题目描述:

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.


非递归:栈实现

import java.util.*;class TreeNode {     int val;     TreeNode left;     TreeNode right;     TreeNode(int x) { val = x; }}public class Solution5 {    public int run(TreeNode root) {        int count = 0;        if(root == null )            return count;          Stack<TreeNode> stack1 = new Stack<TreeNode>();        Stack<TreeNode> stack2 = new Stack<TreeNode>();        stack1.push(root);        while(!stack1.empty() || !stack2.empty()){            count++;            while(!stack1.empty()){            TreeNode t = stack1.peek();            if(t.left != null || t.right != null){                if(t.left != null)                    stack2.push(t.left);                if(t.right != null)                    stack2.push(t.right);            }            else{                return count;            }            stack1.pop();        }            count++;        while(!stack2.empty()){            TreeNode t1 = stack2.peek();           if(t1.left != null || t1.right != null){                if(t1.left != null)                    stack1.push(t1.left);                if(t1.right != null)                    stack1.push(t1.right);            }else{                return count;            }            stack2.pop();        }         }        return 0;    }}


非递归:队列实现

import java.util.*;public class Solution {    public int run(TreeNode root) {        if(root == null)            return 0;        if(root.left == null && root.right == null)            return 1;        int depth = 0;        Queue<TreeNode> queue = new LinkedList<>();        queue.offer(root);        while(!queue.isEmpty()){            int len = queue.size();            depth++;            for(int i = 0; i < len; i++){                TreeNode cur = queue.poll();                            if(cur.left == null && cur.right == null)                    return depth;                if(cur.left != null)                    queue.offer(cur.left);                if(cur.right != null)                    queue.offer(cur.right);            }                       }        return 0;    }}


递归实现:

public class Solution{public int run(TreeNode root){if(root == null)return 0;int l = run(root.left);int r = run(root.right);if(l == 0 || r == 0)return 1 + l + r;return 1 + Math.min(l,r);}}
public class Solution {    public int run(TreeNode root) {        if(root==null)            return 0;        if(root.left==null&&root.right==null)            return 1;        if(root.left==null)            return run(root.right)+1;        if(root.right==null)            return run(root.left)+1;        return Math.min(run(root.left),run(root.right))+1;    }}



原创粉丝点击