1. 程式人生 > >LeetCode——104. 二叉樹的最大深度

LeetCode——104. 二叉樹的最大深度

題目

給定一個二叉樹,找出其最大深度。

二叉樹的深度為根節點到最遠葉子節點的最長路徑上的節點數。

說明: 葉子節點是指沒有子節點的節點。

示例: 給定二叉樹 [3,9,20,null,null,15,7]

    3
   / \
  9  20
    /  \
   15   7

返回它的最大深度 3 。

解題思路 

 遞迴方程: f(n) = 0    n = null

                    f(n) = 1 + max(f(n左),f(n右))

程式碼實現

/**
 * 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) {
        int reInt = 0; //返回值
        
        // 1、如果根節點為空返回0。
        if (root == null) {
            return 0;
        }
        
        // 2、找到最大深度
        int nLeft = maxDepth(root.left);
        int nRight = maxDepth(root.right);
        
        return (nLeft > nRight) ? (nLeft+1) : (nRight+1);
        
       
    }
}

 用遞迴的方法實現容易出現棧溢位問題,因此最好以非遞迴方式實現,找了一個非遞迴實現...

public int treeDepth2(BinaryTreeNode root)  
  {  
     if(root == null)  
         return 0;  
      
     BinaryTreeNode current = null;  
     LinkedList<BinaryTreeNode> queue = new LinkedList<BinaryTreeNode>();  
     queue.offer(root);  
     int cur,last;  
     int level = 0;  
     while(!queue.isEmpty())  
     {  
         cur = 0;//記錄本層已經遍歷的節點個數  
         last = queue.size();//當遍歷完當前層以後,佇列裡元素全是下一層的元素,佇列的長度是這一層的節點的個數  
         while(cur < last)//當還沒有遍歷到本層最後一個節點時迴圈  
         {  
             current = queue.poll();//出隊一個元素  
             cur++;  
             //把當前節點的左右節點入隊(如果存在的話)  
             if(current.left != null)  
             {  
                 queue.offer(current.left);  
             }  
             if(current.right != null)  
             {  
                 queue.offer(current.right);  
             }  
         }  
         level++;//每遍歷完一層level+1  
     }  
     return level;  
  } 

可以看到對於樹想要使用非遞迴實現就要將樹放入佇列或棧等其他結構中。