二叉树求深度

一般来说有两种方案,一种是采用递归的方式,另一种是采用循环迭代的方式模拟递归的栈。

递归方式:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftDep = maxDepth(root.left);
        int rightDep = maxDepth(root.right);
        return Math.max(leftDep, rightDep) + 1;
    }
}

迭代方式:首先得有一个栈存node,可是node的深度信息没有,也得存下来,要不然没法计算。所以需要两个栈

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Stack<TreeNode> nodeStack = new Stack();
        Stack<Integer> depthStack = new Stack();
        nodeStack.push(root);
        depthStack.push(1);
        
        int depth = 0, currentDepth = 0;
        while(!nodeStack.empty()) {
            root = nodeStack.pop();
            currentDepth = depthStack.pop();
            depth = Math.max(depth, currentDepth);
            if (root.right != null) {
                nodeStack.push(root.right);
                depthStack.push(currentDepth + 1);
            }
            if (root.left != null) {
                nodeStack.push(root.left);
                depthStack.push(currentDepth + 1);
            }
        }
        return depth;
    }
}

采用广度优先遍历的解法:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null)
            return 0;
        Queue<TreeNode> queue = new LinkedList();
        queue.offer(root);
        int maxDepth = 0;
        while (!queue.isEmpty()) {
            ++maxDepth;
            int length = queue.size();
            for (int i = 0; i < length; i++) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
        }
        return maxDepth;
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值