2022年9月8日 星期四

814. Binary Tree Pruning

給一個二元樹,若分支下的節點皆為0,則將其分支移除,最後返回同一棵樹。

https://leetcode.com/problems/binary-tree-pruning/





範例
Input: root = [1,0,1,0,0,0,1] Output: [1,null,1,null,1]
使用遞迴來處理。

寫成程式碼如下
public TreeNode pruneTree(TreeNode root) {
    	
    	//使用遞迴判斷分支是否需刪除
    	if(needCut(root)) {
    		//整顆二元樹皆需移除,直接回傳空值
    		return null;
    	}
    	
    	return root;
    }
	
    public boolean needCut(TreeNode root) {
    	
    	boolean left;
    	if(root.left!=null) {
        	//左側分支不為空,則再往下使用遞迴
    		left = needCut(root.left);
    	}else {
    		//為空值,表示需刪除
    		left = true;
    	}
    	boolean right;
    	if(root.right!=null) {
    		//右側分支不為空,則再往下使用遞迴
    		right = needCut(root.right);
    	}else {
    		//為空值,表示需刪除
    		right = true;
    	}
    	
    	//依判斷結果來看左側分支是否需刪除
    	if(left) {
    		root.left = null;
    	}
    	//依判斷結果來看右側分支是否需刪除
    	if(right) {
    		root.right = null;
    	}
    	
    	//再判斷自身節點,是否需刪除並回傳
    	if(root.val!=1 && root.right == null && root.left == null) {
    		return true;
    	}
    	return false;
    }




沒有留言:

張貼留言